├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── diagram.png ├── mvnw ├── mvnw.cmd ├── mykeys.jks ├── pom.xml ├── readme.md ├── src └── main │ ├── java │ └── com │ │ └── tinmegali │ │ ├── DemoOauth2Application.java │ │ ├── controllers │ │ ├── ApiController.java │ │ └── GeneralController.java │ │ ├── exceptions │ │ └── RestError.java │ │ ├── models │ │ ├── Account.java │ │ └── RestResponse.java │ │ ├── repositories │ │ └── AccountRepo.java │ │ ├── security │ │ ├── AuthorizationServerConfig.java │ │ ├── ResourceConfig.java │ │ ├── SecretKeyProvider.java │ │ └── SecurityConfig.java │ │ └── services │ │ └── AccountService.java │ └── resources │ └── application.properties └── tinmegali.uml /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | diagram.png 18 | tinmegali.uml 19 | 20 | 21 | ### NetBeans ### 22 | nbproject/private/ 23 | build/ 24 | nbbuild/ 25 | dist/ 26 | nbdist/ 27 | .nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinmegali/Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token/317a1bdbda7fe6d88c8c41f37a39caddb7cb5426/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Tin Megali 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinmegali/Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token/317a1bdbda7fe6d88c8c41f37a39caddb7cb5426/diagram.png -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /mykeys.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinmegali/Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token/317a1bdbda7fe6d88c8c41f37a39caddb7cb5426/mykeys.jks -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.tinmegali 7 | demo-oauth2 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | demo-oauth2 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Dalston.SR1 26 | 27 | 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-starter-oauth2 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-jpa 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-security 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-web 44 | 45 | 46 | 47 | com.h2database 48 | h2 49 | runtime 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.cloud 62 | spring-cloud-dependencies 63 | ${spring-cloud.version} 64 | pom 65 | import 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-maven-plugin 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 | Oauth2 Stateless Authentication with Spring and JWT Token 3 |

4 |

5 | This project uses Spring Security to authenticate and protect some Rest resources. 6 | It uses withAuthorizationServerConfigurerAdapter, ResourceServerConfigurerAdapter 7 | and WebSecurityConfigurerAdapter combined with @PreAuthorize to configure the security. 8 | It also uses an H2 embeded database to authenticate the users. 9 |

10 | 11 |

Article on the project

12 | USING SPRING OAUTH2 TO SECURE REST 13 | 14 |

External references

15 | This project was inspired by all these references. 16 |
  • Using JWT with Spring Security OAuth 17 |
  • JWT authentication with Spring Web 18 |
  • JWT Authentication Tutorial: An example using Spring Boot 19 |
  • Spring Oauth2 with JWT Sample 20 |
  • OAuth2 in depth: A step-by-step introduction for enterprises 21 |
  • spring-auth-example 22 | 23 |

    To Build and Run

    24 | Go to the cloned directory and run mvn spring-boot:run or build with your chosen IDE. 25 | 26 |

    Curl Commands

    27 | You should install ./JQ before running these Curl commands. 28 |
    29 | To get a new token
    30 | 31 | curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=password" | jq 32 | 33 | 34 |
    35 | To get a refresh token
    36 | 37 | curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=access_token&access_tokem=[ACCESS_TOKEN]" | jq 38 | 39 | 40 | 41 |
    42 | To access a protected resource
    43 | 44 | curl -H "Authorization: Bearer [ACCESS_TOKEN]" localhost:8080/api/hello 45 | 46 |
    47 | 48 |

    49 | Register new Account
    50 | 51 | curl -H "Authorization: Bearer $(curl register-app:secret@localhost:8080/oauth/token -d "grant_type=client_credentials&client_id=register-app" | jq --raw-output ."access_token")" localhost:8080/api/register -H "Content-Type: application/json" -d '{"username":"new-user","password":"password","firstName":"First","lastName":"Last","email":"email@email.com"}' | jq 52 | 53 |

    54 | 55 |
    56 |

    57 | Curl sample commands 58 | api/me 59 | 60 | curl -H "Authorization: Bearer $(curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=password" | jq --raw-output ."access_token")" localhost:8080/api/me | jq 61 | 62 |

    63 |
    -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/DemoOauth2Application.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali; 2 | 3 | import com.tinmegali.models.Account; 4 | import com.tinmegali.services.AccountService; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; 11 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 12 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | 15 | import javax.security.auth.login.AccountException; 16 | import javax.sql.DataSource; 17 | import java.util.Arrays; 18 | 19 | @SpringBootApplication 20 | public class DemoOauth2Application { 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(DemoOauth2Application.class, args); 24 | } 25 | 26 | @Bean 27 | public BCryptPasswordEncoder passwordEncoder(){ 28 | return new BCryptPasswordEncoder(); 29 | } 30 | 31 | @Bean @Qualifier("mainDataSource") 32 | public DataSource dataSource(){ 33 | EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); 34 | EmbeddedDatabase db = builder 35 | .setType(EmbeddedDatabaseType.H2) 36 | .build(); 37 | return db; 38 | } 39 | 40 | @Bean 41 | CommandLineRunner init( 42 | AccountService accountService 43 | ) { 44 | return (evt) -> Arrays.asList( 45 | "user,admin,john,robert,ana".split(",")).forEach( 46 | username -> { 47 | Account acct = new Account(); 48 | acct.setUsername(username); 49 | if ( username.equals("user")) acct.setPassword("password"); 50 | else acct.setPassword(passwordEncoder().encode("password")); 51 | acct.setFirstName(username); 52 | acct.setLastName("LastName"); 53 | acct.grantAuthority("ROLE_USER"); 54 | if ( username.equals("admin") ) 55 | acct.grantAuthority("ROLE_ADMIN"); 56 | try { 57 | accountService.register(acct); 58 | } catch (AccountException e) { 59 | e.printStackTrace(); 60 | } 61 | } 62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/controllers/ApiController.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.controllers; 2 | 3 | import com.tinmegali.exceptions.RestError; 4 | import com.tinmegali.models.Account; 5 | import com.tinmegali.models.RestResponse; 6 | import com.tinmegali.services.AccountService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.access.prepost.PreAuthorize; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 15 | import org.springframework.web.bind.annotation.*; 16 | 17 | import javax.security.auth.login.AccountException; 18 | 19 | @RestController 20 | public class ApiController { 21 | 22 | @Autowired 23 | private AccountService accountService; 24 | 25 | @GetMapping("/api/hello") 26 | public ResponseEntity hello() { 27 | String name = SecurityContextHolder.getContext().getAuthentication().getName(); 28 | String msg = String.format("Hello %s", name); 29 | return new ResponseEntity(msg, HttpStatus.OK); 30 | } 31 | 32 | @GetMapping(path = "/api/me", produces = "application/json" ) 33 | public Account me() { 34 | String username = SecurityContextHolder.getContext().getAuthentication().getName(); 35 | return accountService.findAccountByUsername(username); 36 | } 37 | 38 | @PostMapping(path = "/api/register", produces = "application/json") 39 | public ResponseEntity register(@RequestBody Account account) { 40 | try { 41 | account.grantAuthority("ROLE_USER"); 42 | return new ResponseEntity( 43 | accountService.register( account ), HttpStatus.OK); 44 | } catch (AccountException e) { 45 | e.printStackTrace(); 46 | return new ResponseEntity(new RestError(e.getMessage()),HttpStatus.BAD_REQUEST ); 47 | } 48 | } 49 | 50 | @PreAuthorize("hasRole('USER')") 51 | @DeleteMapping(path = "/api/user/remove", produces = "application/json") 52 | public ResponseEntity removeUser() { 53 | try { 54 | accountService.removeAuthenticatedAccount(); 55 | return new ResponseEntity(new RestResponse("User removed."), HttpStatus.OK); 56 | } catch (UsernameNotFoundException e) { 57 | e.printStackTrace(); 58 | return new ResponseEntity(new RestError(e.getMessage()), HttpStatus.OK); 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/controllers/GeneralController.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.controllers; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.util.MultiValueMap; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | @RestController 8 | public class GeneralController { 9 | 10 | @RequestMapping("/") 11 | public String home() { 12 | return "Hello World"; 13 | } 14 | 15 | @RequestMapping(value = "/", method = RequestMethod.POST) 16 | @ResponseStatus(HttpStatus.CREATED) 17 | public String create(@RequestBody MultiValueMap map) { 18 | return "OK"; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/exceptions/RestError.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.exceptions; 2 | 3 | public class RestError { 4 | 5 | private String message; 6 | 7 | public RestError(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/models/Account.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.models; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | 7 | import javax.persistence.*; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | @Entity 12 | public class Account implements UserDetails { 13 | 14 | @Id 15 | @GeneratedValue(strategy=GenerationType.SEQUENCE) 16 | private Long id; 17 | 18 | private String username; 19 | private String password; 20 | 21 | private String firstName; 22 | private String lastName; 23 | private String email; 24 | 25 | @ElementCollection(fetch = FetchType.EAGER) 26 | private List roles; 27 | 28 | private boolean accountNonExpired, accountNonLocked, credentialsNonExpired, enabled; 29 | 30 | public Account() { 31 | this.accountNonExpired = true; 32 | this.accountNonLocked = true; 33 | this.credentialsNonExpired = true; 34 | this.enabled = true; 35 | } 36 | 37 | @Override 38 | public boolean isAccountNonExpired() { 39 | return accountNonExpired; 40 | } 41 | 42 | @Override 43 | public boolean isAccountNonLocked() { 44 | return accountNonLocked; 45 | } 46 | 47 | @Override 48 | public boolean isCredentialsNonExpired() { 49 | return credentialsNonExpired; 50 | } 51 | 52 | @Override 53 | public boolean isEnabled() { 54 | return enabled; 55 | } 56 | 57 | public void grantAuthority(String authority) { 58 | if ( roles == null ) roles = new ArrayList<>(); 59 | roles.add(authority); 60 | } 61 | 62 | @Override 63 | public List getAuthorities(){ 64 | List authorities = new ArrayList<>(); 65 | roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); 66 | return authorities; 67 | } 68 | 69 | public List getRoles() { 70 | return roles; 71 | } 72 | 73 | public void setRoles(List roles) { 74 | this.roles = roles; 75 | } 76 | 77 | public String getPassword() { 78 | return password; 79 | } 80 | 81 | public void setPassword(String password) { 82 | this.password = password; 83 | } 84 | 85 | public Long getId() { 86 | return id; 87 | } 88 | 89 | public void setId(Long id) { 90 | this.id = id; 91 | } 92 | 93 | public void setAccountNonExpired(boolean accountNonExpired) { 94 | this.accountNonExpired = accountNonExpired; 95 | } 96 | 97 | public void setAccountNonLocked(boolean accountNonLocked) { 98 | this.accountNonLocked = accountNonLocked; 99 | } 100 | 101 | public void setCredentialsNonExpired(boolean credentialsNonExpired) { 102 | this.credentialsNonExpired = credentialsNonExpired; 103 | } 104 | 105 | public void setEnabled(boolean enabled) { 106 | this.enabled = enabled; 107 | } 108 | 109 | public String getUsername() { 110 | return username; 111 | } 112 | 113 | public void setUsername(String username) { 114 | this.username = username; 115 | } 116 | 117 | public String getFirstName() { 118 | return firstName; 119 | } 120 | 121 | public void setFirstName(String firstName) { 122 | this.firstName = firstName; 123 | } 124 | 125 | public String getLastName() { 126 | return lastName; 127 | } 128 | 129 | public void setLastName(String lastName) { 130 | this.lastName = lastName; 131 | } 132 | 133 | public String getEmail() { 134 | return email; 135 | } 136 | 137 | public void setEmail(String email) { 138 | this.email = email; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/models/RestResponse.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.models; 2 | 3 | /** 4 | * Created by tinmegali on 20/06/17. 5 | */ 6 | public class RestResponse { 7 | 8 | String msg; 9 | 10 | public RestResponse(String msg) { 11 | this.msg = msg; 12 | } 13 | 14 | public String getMsg() { 15 | return msg; 16 | } 17 | 18 | public void setMsg(String msg) { 19 | this.msg = msg; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/repositories/AccountRepo.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.repositories; 2 | 3 | 4 | import com.tinmegali.models.Account; 5 | import org.springframework.data.repository.Repository; 6 | 7 | import java.util.Collection; 8 | import java.util.Optional; 9 | 10 | public interface AccountRepo extends Repository { 11 | 12 | Collection findAll(); 13 | Optional findByUsername(String username); 14 | Optional findById(Long id); 15 | Integer countByUsername(String username); 16 | Account save(Account account); 17 | void deleteAccountById(Long id); 18 | 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/security/AuthorizationServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.security; 2 | 3 | import com.tinmegali.services.AccountService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Primary; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 12 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 13 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 14 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 15 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 16 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 17 | import org.springframework.security.oauth2.provider.token.TokenStore; 18 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 19 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 20 | 21 | import java.io.IOException; 22 | import java.net.URISyntaxException; 23 | import java.security.KeyStoreException; 24 | import java.security.NoSuchAlgorithmException; 25 | import java.security.UnrecoverableKeyException; 26 | import java.security.cert.CertificateException; 27 | 28 | @Configuration 29 | @EnableAuthorizationServer 30 | public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 31 | 32 | @Value("${security.oauth2.resource.id}") 33 | private String resourceId; 34 | 35 | @Value("${access_token.validity_period}") 36 | private int accessTokenValiditySeconds; 37 | 38 | @Value("${refresh_token.validity_period}") 39 | private int refreshTokenValiditySeconds; 40 | 41 | @Autowired 42 | private AuthenticationManager authenticationManager; 43 | 44 | @Bean 45 | public UserDetailsService userDetailsService(){ 46 | return new AccountService(); 47 | } 48 | 49 | @Override 50 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 51 | endpoints 52 | .authenticationManager(this.authenticationManager) 53 | .tokenServices(tokenServices()) 54 | .tokenStore(tokenStore()) 55 | .accessTokenConverter(accessTokenConverter()); 56 | } 57 | 58 | @Override 59 | public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 60 | oauthServer 61 | .tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')") 62 | .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')"); 63 | } 64 | 65 | @Override 66 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 67 | clients.inMemory() 68 | .withClient("normal-app") 69 | .authorizedGrantTypes("authorization_code", "implicit") 70 | .authorities("ROLE_CLIENT") 71 | .scopes("read", "write") 72 | .resourceIds(resourceId) 73 | .accessTokenValiditySeconds(accessTokenValiditySeconds) 74 | .refreshTokenValiditySeconds(refreshTokenValiditySeconds) 75 | .and() 76 | .withClient("trusted-app") 77 | .authorizedGrantTypes("client_credentials", "password", "refresh_token") 78 | .authorities("ROLE_TRUSTED_CLIENT") 79 | .scopes("read", "write") 80 | .resourceIds(resourceId) 81 | .accessTokenValiditySeconds(accessTokenValiditySeconds) 82 | .refreshTokenValiditySeconds(refreshTokenValiditySeconds) 83 | .secret("secret") 84 | .and() 85 | .withClient("register-app") 86 | .authorizedGrantTypes("client_credentials") 87 | .authorities("ROLE_REGISTER") 88 | .scopes("read") 89 | .resourceIds(resourceId) 90 | .secret("secret") 91 | .and() 92 | .withClient("my-client-with-registered-redirect") 93 | .authorizedGrantTypes("authorization_code") 94 | .authorities("ROLE_CLIENT") 95 | .scopes("read", "trust") 96 | .resourceIds("oauth2-resource") 97 | .redirectUris("http://anywhere?key=value"); 98 | } 99 | 100 | @Bean 101 | public TokenStore tokenStore() { 102 | return new JwtTokenStore(accessTokenConverter()); 103 | } 104 | 105 | @Autowired 106 | private SecretKeyProvider keyProvider; 107 | 108 | @Bean 109 | public JwtAccessTokenConverter accessTokenConverter() { 110 | JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); 111 | try { 112 | converter.setSigningKey(keyProvider.getKey()); 113 | } catch (URISyntaxException | KeyStoreException | NoSuchAlgorithmException | IOException | UnrecoverableKeyException | CertificateException e) { 114 | e.printStackTrace(); 115 | } 116 | 117 | return converter; 118 | } 119 | 120 | @Bean 121 | @Primary 122 | public DefaultTokenServices tokenServices() { 123 | DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); 124 | defaultTokenServices.setTokenStore(tokenStore()); 125 | defaultTokenServices.setSupportRefreshToken(true); 126 | defaultTokenServices.setTokenEnhancer(accessTokenConverter()); 127 | return defaultTokenServices; 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/security/ResourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 10 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 11 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 12 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 13 | import org.springframework.security.oauth2.provider.token.TokenStore; 14 | import org.springframework.security.web.util.matcher.RequestMatcher; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | 18 | 19 | @Configuration 20 | @EnableResourceServer 21 | @EnableGlobalMethodSecurity(prePostEnabled=true) 22 | public class ResourceConfig extends ResourceServerConfigurerAdapter { 23 | 24 | @Value("${security.oauth2.resource.id}") 25 | private String resourceId; 26 | 27 | @Autowired 28 | private DefaultTokenServices tokenServices; 29 | 30 | @Autowired 31 | private TokenStore tokenStore; 32 | 33 | @Override 34 | public void configure(ResourceServerSecurityConfigurer resources) { 35 | resources 36 | .resourceId(resourceId) 37 | .tokenServices(tokenServices) 38 | .tokenStore(tokenStore); 39 | } 40 | 41 | @Override 42 | public void configure(HttpSecurity http) throws Exception { 43 | http.requestMatcher(new OAuthRequestedMatcher()) 44 | .anonymous().disable() 45 | .authorizeRequests() 46 | .antMatchers(HttpMethod.OPTIONS).permitAll() 47 | .antMatchers("/api/hello").access("hasAnyRole('USER')") 48 | .antMatchers("/api/me").hasAnyRole("USER", "ADMIN") 49 | .antMatchers("/api/register").hasAuthority("ROLE_REGISTER"); 50 | } 51 | 52 | private static class OAuthRequestedMatcher implements RequestMatcher { 53 | public boolean matches(HttpServletRequest request) { 54 | String auth = request.getHeader("Authorization"); 55 | // Determine if the client request contained an OAuth Authorization 56 | boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer"); 57 | boolean haveAccessToken = request.getParameter("access_token")!=null; 58 | return haveOauth2Token || haveAccessToken; 59 | } 60 | } 61 | 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/security/SecretKeyProvider.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.security; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | import java.net.URISyntaxException; 8 | import java.security.*; 9 | import java.security.cert.Certificate; 10 | import java.security.cert.CertificateException; 11 | 12 | /** 13 | * Based on http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm 14 | */ 15 | @Component 16 | public class SecretKeyProvider { 17 | 18 | public String getKey() throws URISyntaxException, 19 | KeyStoreException, IOException, 20 | NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException{ 21 | return new String( getKeyPair().getPublic().getEncoded(), "UTF-8" ); 22 | } 23 | 24 | private KeyPair getKeyPair() throws 25 | KeyStoreException, IOException, 26 | NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { 27 | FileInputStream is = new FileInputStream("mykeys.jks"); 28 | 29 | KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 30 | keystore.load(is, "mypass".toCharArray()); 31 | 32 | String alias = "mykeys"; 33 | 34 | Key key = keystore.getKey(alias, "mypass".toCharArray()); 35 | if (key instanceof PrivateKey) { 36 | // Get certificate of public key 37 | Certificate cert = keystore.getCertificate(alias); 38 | 39 | // Get public key 40 | PublicKey publicKey = cert.getPublicKey(); 41 | 42 | // Return a key pair 43 | return new KeyPair(publicKey, (PrivateKey) key); 44 | } else throw new UnrecoverableKeyException(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/security/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.autoconfigure.security.SecurityProperties; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.core.userdetails.UserDetailsService; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | 18 | @Configuration 19 | @EnableWebSecurity( debug = true ) 20 | @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 21 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 22 | 23 | @Autowired 24 | public UserDetailsService userDetailsService; 25 | 26 | @Autowired 27 | private PasswordEncoder passwordEncoder; 28 | 29 | @Bean 30 | public DaoAuthenticationProvider authenticationProvider() { 31 | DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); 32 | provider.setPasswordEncoder( passwordEncoder ); 33 | provider.setUserDetailsService(userDetailsService()); 34 | return provider; 35 | } 36 | 37 | @Override 38 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 39 | auth 40 | .userDetailsService(userDetailsService) 41 | .passwordEncoder(passwordEncoder); 42 | } 43 | 44 | @Override 45 | protected void configure(HttpSecurity http) throws Exception { 46 | http 47 | .authorizeRequests() 48 | .anyRequest().authenticated() 49 | .antMatchers("/","/**").permitAll() 50 | .antMatchers(HttpMethod.OPTIONS).permitAll() 51 | .and().httpBasic().and() 52 | .csrf().disable(); 53 | } 54 | 55 | @Override 56 | @Bean 57 | public AuthenticationManager authenticationManagerBean() throws Exception { 58 | return super.authenticationManagerBean(); 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/tinmegali/services/AccountService.java: -------------------------------------------------------------------------------- 1 | package com.tinmegali.services; 2 | 3 | import com.tinmegali.models.Account; 4 | import com.tinmegali.repositories.AccountRepo; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import javax.security.auth.login.AccountException; 15 | import java.util.Optional; 16 | 17 | @Service 18 | public class AccountService implements UserDetailsService { 19 | 20 | @Autowired 21 | private AccountRepo accountRepo; 22 | 23 | @Autowired 24 | private PasswordEncoder passwordEncoder; 25 | 26 | @Override 27 | public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { 28 | Optional account = accountRepo.findByUsername( s ); 29 | if ( account.isPresent() ) { 30 | return account.get(); 31 | } else { 32 | throw new UsernameNotFoundException(String.format("Username[%s] not found", s)); 33 | } 34 | } 35 | 36 | public Account findAccountByUsername(String username) throws UsernameNotFoundException { 37 | Optional account = accountRepo.findByUsername( username ); 38 | if ( account.isPresent() ) { 39 | return account.get(); 40 | } else { 41 | throw new UsernameNotFoundException(String.format("Username[%s] not found", username)); 42 | } 43 | 44 | } 45 | 46 | public Account register(Account account) throws AccountException { 47 | if ( accountRepo.countByUsername( account.getUsername() ) == 0 ) { 48 | account.setPassword(passwordEncoder.encode(account.getPassword())); 49 | return accountRepo.save( account ); 50 | } else { 51 | throw new AccountException(String.format("Username[%s] already taken.", account.getUsername())); 52 | } 53 | } 54 | 55 | @Transactional // To successfully remove the date @Transactional annotation must be added 56 | public void removeAuthenticatedAccount() throws UsernameNotFoundException { 57 | String username = SecurityContextHolder.getContext().getAuthentication().getName(); 58 | Account acct = findAccountByUsername(username); 59 | accountRepo.deleteAccountById(acct.getId()); 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #security.oauth2.resource.filter-order=3 2 | 3 | spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE 4 | spring.datasource.driverClassName=org.h2.Driver 5 | spring.datasource.username=sa 6 | spring.datasource.password= 7 | spring.h2.console.enabled=true 8 | 9 | security.oauth2.resource.id=oauth2_application 10 | access_token.validity_period=3600 11 | refresh_token.validity_period=10000 12 | 13 | -------------------------------------------------------------------------------- /tinmegali.uml: -------------------------------------------------------------------------------- 1 | 2 | 3 | JAVA 4 | com.tinmegali 5 | 6 | com.tinmegali.models.RestResponse 7 | com.tinmegali.controllers.ApiController 8 | com.tinmegali.DemoOauth2Application 9 | com.tinmegali.security.ResourceConfig 10 | com.tinmegali.controllers.GeneralController 11 | com.tinmegali.repositories.AccountRepo 12 | com.tinmegali.security.ResourceConfig.OAuthRequestedMatcher 13 | com.tinmegali.security.AuthorizationServerConfig 14 | com.tinmegali.security.SecurityConfig 15 | com.tinmegali.security.SecretKeyProvider 16 | com.tinmegali.services.AccountService 17 | com.tinmegali.models.Account 18 | com.tinmegali.exceptions.RestError 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | Methods 59 | Properties 60 | 61 | All 62 | private 63 | 64 | 65 | --------------------------------------------------------------------------------