├── .DS_Store ├── .gitignore ├── LICENSE ├── README.md ├── bin ├── main │ ├── application.properties │ └── com │ │ └── djamware │ │ └── SecurityRest │ │ ├── SecurityRestApplication.class │ │ ├── configs │ │ ├── JwtConfigurer.class │ │ ├── JwtTokenFilter.class │ │ ├── JwtTokenProvider.class │ │ └── WebSecurityConfig.class │ │ ├── controllers │ │ ├── AuthBody.class │ │ ├── AuthController.class │ │ └── ProductController.class │ │ ├── models │ │ ├── Product.class │ │ ├── Role.class │ │ └── User.class │ │ ├── repositories │ │ ├── ProductRepository.class │ │ ├── RoleRepository.class │ │ └── UserRepository.class │ │ └── services │ │ └── CustomUserDetailsService.class └── test │ └── com │ └── djamware │ └── SecurityRest │ └── SecurityRestApplicationTests.class ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── .DS_Store ├── main ├── .DS_Store ├── java │ ├── .DS_Store │ └── com │ │ ├── .DS_Store │ │ └── djamware │ │ ├── .DS_Store │ │ └── SecurityRest │ │ ├── .DS_Store │ │ ├── SecurityRestApplication.java │ │ ├── configs │ │ ├── JwtConfigurer.java │ │ ├── JwtTokenFilter.java │ │ ├── JwtTokenProvider.java │ │ └── WebSecurityConfig.java │ │ ├── controllers │ │ ├── AuthBody.java │ │ ├── AuthController.java │ │ └── ProductController.java │ │ ├── models │ │ ├── Product.java │ │ ├── Role.java │ │ └── User.java │ │ ├── repositories │ │ ├── ProductRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ └── services │ │ └── CustomUserDetailsService.java └── resources │ └── application.properties └── test └── java └── com └── djamware └── SecurityRest └── SecurityRestApplicationTests.java /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | /out/ 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Didin Jamaludin 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Securing RESTful API with Spring Boot, Security, and Data MongoDB 2 | 3 | This source code is part of [Securing RESTful API with Spring Boot, Security, and Data MongoDB](https://www.djamware.com/post/5c819d0180aca754f7a9d1ee/securing-restful-api-with-spring-boot-security-and-data-mongodb) tutorial. 4 | -------------------------------------------------------------------------------- /bin/main/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.database=springmongodb 2 | spring.data.mongodb.host=localhost 3 | spring.data.mongodb.port=27017 -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/SecurityRestApplication.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/SecurityRestApplication.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/configs/JwtConfigurer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/configs/JwtConfigurer.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/configs/JwtTokenFilter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/configs/JwtTokenFilter.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/configs/JwtTokenProvider.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/configs/JwtTokenProvider.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/configs/WebSecurityConfig.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/configs/WebSecurityConfig.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/controllers/AuthBody.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/controllers/AuthBody.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/controllers/AuthController.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/controllers/AuthController.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/controllers/ProductController.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/controllers/ProductController.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/models/Product.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/models/Product.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/models/Role.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/models/Role.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/models/User.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/models/User.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/repositories/ProductRepository.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/repositories/ProductRepository.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/repositories/RoleRepository.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/repositories/RoleRepository.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/repositories/UserRepository.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/repositories/UserRepository.class -------------------------------------------------------------------------------- /bin/main/com/djamware/SecurityRest/services/CustomUserDetailsService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/main/com/djamware/SecurityRest/services/CustomUserDetailsService.class -------------------------------------------------------------------------------- /bin/test/com/djamware/SecurityRest/SecurityRestApplicationTests.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/bin/test/com/djamware/SecurityRest/SecurityRestApplicationTests.class -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.1.2.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'org.springframework.boot' 15 | apply plugin: 'io.spring.dependency-management' 16 | 17 | group = 'com.djamware' 18 | version = '0.0.1-SNAPSHOT' 19 | sourceCompatibility = '1.8' 20 | 21 | repositories { 22 | mavenCentral() 23 | } 24 | 25 | dependencies { 26 | implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' 27 | implementation 'org.springframework.boot:spring-boot-starter-security' 28 | implementation 'org.springframework.boot:spring-boot-starter-web' 29 | implementation 'io.jsonwebtoken:jjwt:0.9.1' 30 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 31 | testImplementation 'org.springframework.security:spring-security-test' 32 | } 33 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'SecurityRest' 2 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/.DS_Store -------------------------------------------------------------------------------- /src/main/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/main/.DS_Store -------------------------------------------------------------------------------- /src/main/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/main/java/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/main/java/com/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/djamware/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/main/java/com/djamware/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/spring-boot-security-rest/d1db1cbb4a8ce46b156e32c001f8a84cde0b3726/src/main/java/com/djamware/SecurityRest/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/SecurityRestApplication.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest; 2 | 3 | import org.springframework.boot.CommandLineRunner; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Bean; 7 | 8 | import com.djamware.SecurityRest.models.Role; 9 | import com.djamware.SecurityRest.repositories.RoleRepository; 10 | 11 | @SpringBootApplication 12 | public class SecurityRestApplication { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(SecurityRestApplication.class, args); 16 | } 17 | 18 | @Bean 19 | CommandLineRunner init(RoleRepository roleRepository) { 20 | 21 | return args -> { 22 | 23 | Role adminRole = roleRepository.findByRole("ADMIN"); 24 | if (adminRole == null) { 25 | Role newAdminRole = new Role(); 26 | newAdminRole.setRole("ADMIN"); 27 | roleRepository.save(newAdminRole); 28 | } 29 | 30 | Role userRole = roleRepository.findByRole("USER"); 31 | if (userRole == null) { 32 | Role newUserRole = new Role(); 33 | newUserRole.setRole("USER"); 34 | roleRepository.save(newUserRole); 35 | } 36 | }; 37 | 38 | } 39 | 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/configs/JwtConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.configs; 2 | 3 | import org.springframework.security.config.annotation.SecurityConfigurerAdapter; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.web.DefaultSecurityFilterChain; 6 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 7 | 8 | public class JwtConfigurer extends SecurityConfigurerAdapter { 9 | 10 | private JwtTokenProvider jwtTokenProvider; 11 | 12 | public JwtConfigurer(JwtTokenProvider jwtTokenProvider) { 13 | this.jwtTokenProvider = jwtTokenProvider; 14 | } 15 | 16 | @Override 17 | public void configure(HttpSecurity http) throws Exception { 18 | JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider); 19 | http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/configs/JwtTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.configs; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.ServletRequest; 8 | import javax.servlet.ServletResponse; 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.web.filter.GenericFilterBean; 14 | 15 | public class JwtTokenFilter extends GenericFilterBean { 16 | 17 | private JwtTokenProvider jwtTokenProvider; 18 | 19 | public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) { 20 | this.jwtTokenProvider = jwtTokenProvider; 21 | } 22 | 23 | @Override 24 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) 25 | throws IOException, ServletException { 26 | String token = jwtTokenProvider.resolveToken((HttpServletRequest) req); 27 | if (token != null && jwtTokenProvider.validateToken(token)) { 28 | Authentication auth = token != null ? jwtTokenProvider.getAuthentication(token) : null; 29 | SecurityContextHolder.getContext().setAuthentication(auth); 30 | } 31 | filterChain.doFilter(req, res); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/configs/JwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.configs; 2 | 3 | import java.util.Base64; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.stereotype.Component; 16 | 17 | import com.djamware.SecurityRest.models.Role; 18 | import com.djamware.SecurityRest.services.CustomUserDetailsService; 19 | 20 | import io.jsonwebtoken.Claims; 21 | import io.jsonwebtoken.Jws; 22 | import io.jsonwebtoken.JwtException; 23 | import io.jsonwebtoken.Jwts; 24 | import io.jsonwebtoken.SignatureAlgorithm; 25 | 26 | @Component 27 | public class JwtTokenProvider { 28 | 29 | @Value("${security.jwt.token.secret-key:secret}") 30 | private String secretKey = "secret"; 31 | 32 | @Value("${security.jwt.token.expire-length:3600000}") 33 | private long validityInMilliseconds = 3600000; // 1h 34 | 35 | @Autowired 36 | private CustomUserDetailsService userDetailsService; 37 | 38 | @PostConstruct 39 | protected void init() { 40 | secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); 41 | } 42 | 43 | public String createToken(String username, Set set) { 44 | Claims claims = Jwts.claims().setSubject(username); 45 | claims.put("roles", set); 46 | Date now = new Date(); 47 | Date validity = new Date(now.getTime() + validityInMilliseconds); 48 | return Jwts.builder()// 49 | .setClaims(claims)// 50 | .setIssuedAt(now)// 51 | .setExpiration(validity)// 52 | .signWith(SignatureAlgorithm.HS256, secretKey)// 53 | .compact(); 54 | } 55 | 56 | public Authentication getAuthentication(String token) { 57 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(getUsername(token)); 58 | return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); 59 | } 60 | 61 | public String getUsername(String token) { 62 | return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); 63 | } 64 | 65 | public String resolveToken(HttpServletRequest req) { 66 | String bearerToken = req.getHeader("Authorization"); 67 | if (bearerToken != null && bearerToken.startsWith("Bearer ")) { 68 | return bearerToken.substring(7, bearerToken.length()); 69 | } 70 | return null; 71 | } 72 | 73 | public boolean validateToken(String token) { 74 | try { 75 | Jws claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); 76 | if (claims.getBody().getExpiration().before(new Date())) { 77 | return false; 78 | } 79 | return true; 80 | } catch (JwtException | IllegalArgumentException e) { 81 | throw new JwtException("Expired or invalid JWT token"); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/configs/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.configs; 2 | 3 | import javax.servlet.http.HttpServletResponse; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 12 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 14 | import org.springframework.security.config.http.SessionCreationPolicy; 15 | import org.springframework.security.core.userdetails.UserDetailsService; 16 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 17 | import org.springframework.security.crypto.password.PasswordEncoder; 18 | import org.springframework.security.web.AuthenticationEntryPoint; 19 | 20 | import com.djamware.SecurityRest.services.CustomUserDetailsService; 21 | 22 | @Configuration 23 | @EnableWebSecurity 24 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 25 | 26 | @Autowired 27 | JwtTokenProvider jwtTokenProvider; 28 | 29 | @Override 30 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 31 | UserDetailsService userDetailsService = mongoUserDetails(); 32 | auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); 33 | 34 | } 35 | 36 | @Override 37 | protected void configure(HttpSecurity http) throws Exception { 38 | http.httpBasic().disable().csrf().disable().sessionManagement() 39 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() 40 | .antMatchers("/api/auth/login").permitAll().antMatchers("/api/auth/register").permitAll() 41 | .antMatchers("/api/products/**").hasAuthority("ADMIN").anyRequest().authenticated().and().csrf() 42 | .disable().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint()).and() 43 | .apply(new JwtConfigurer(jwtTokenProvider)); 44 | } 45 | 46 | @Override 47 | public void configure(WebSecurity web) throws Exception { 48 | web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**"); 49 | } 50 | 51 | @Bean 52 | public PasswordEncoder bCryptPasswordEncoder() { 53 | return new BCryptPasswordEncoder(); 54 | } 55 | 56 | @Bean 57 | @Override 58 | public AuthenticationManager authenticationManagerBean() throws Exception { 59 | return super.authenticationManagerBean(); 60 | } 61 | 62 | @Bean 63 | public AuthenticationEntryPoint unauthorizedEntryPoint() { 64 | return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 65 | "Unauthorized"); 66 | } 67 | 68 | @Bean 69 | public UserDetailsService mongoUserDetails() { 70 | return new CustomUserDetailsService(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/controllers/AuthBody.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.controllers; 2 | 3 | public class AuthBody { 4 | 5 | private String email; 6 | private String password; 7 | 8 | public String getEmail() { 9 | return email; 10 | } 11 | public void setEmail(String email) { 12 | this.email = email; 13 | } 14 | public String getPassword() { 15 | return password; 16 | } 17 | public void setPassword(String password) { 18 | this.password = password; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/controllers/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.controllers; 2 | 3 | import static org.springframework.http.ResponseEntity.ok; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.authentication.BadCredentialsException; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.web.bind.annotation.PostMapping; 15 | import org.springframework.web.bind.annotation.RequestBody; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.RestController; 18 | 19 | import com.djamware.SecurityRest.configs.JwtTokenProvider; 20 | import com.djamware.SecurityRest.models.User; 21 | import com.djamware.SecurityRest.repositories.UserRepository; 22 | import com.djamware.SecurityRest.services.CustomUserDetailsService; 23 | 24 | @RestController 25 | @RequestMapping("/api/auth") 26 | public class AuthController { 27 | 28 | @Autowired 29 | AuthenticationManager authenticationManager; 30 | 31 | @Autowired 32 | JwtTokenProvider jwtTokenProvider; 33 | 34 | @Autowired 35 | UserRepository users; 36 | 37 | @Autowired 38 | private CustomUserDetailsService userService; 39 | 40 | @SuppressWarnings("rawtypes") 41 | @PostMapping("/login") 42 | public ResponseEntity login(@RequestBody AuthBody data) { 43 | try { 44 | String username = data.getEmail(); 45 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword())); 46 | String token = jwtTokenProvider.createToken(username, this.users.findByEmail(username).getRoles()); 47 | Map model = new HashMap<>(); 48 | model.put("username", username); 49 | model.put("token", token); 50 | return ok(model); 51 | } catch (AuthenticationException e) { 52 | throw new BadCredentialsException("Invalid email/password supplied"); 53 | } 54 | } 55 | 56 | @SuppressWarnings("rawtypes") 57 | @PostMapping("/register") 58 | public ResponseEntity register(@RequestBody User user) { 59 | User userExists = userService.findUserByEmail(user.getEmail()); 60 | if (userExists != null) { 61 | throw new BadCredentialsException("User with username: " + user.getEmail() + " already exists"); 62 | } 63 | userService.saveUser(user); 64 | Map model = new HashMap<>(); 65 | model.put("message", "User registered successfully"); 66 | return ok(model); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/controllers/ProductController.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.controllers; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import com.djamware.SecurityRest.models.Product; 13 | import com.djamware.SecurityRest.repositories.ProductRepository; 14 | 15 | @RestController 16 | public class ProductController { 17 | 18 | @Autowired 19 | ProductRepository productRepository; 20 | 21 | @RequestMapping(method=RequestMethod.GET, value="/api/products") 22 | public Iterable product() { 23 | return productRepository.findAll(); 24 | } 25 | 26 | @RequestMapping(method=RequestMethod.POST, value="/api/products") 27 | public String save(@RequestBody Product product) { 28 | productRepository.save(product); 29 | 30 | return product.getId(); 31 | } 32 | 33 | @RequestMapping(method=RequestMethod.GET, value="/api/products/{id}") 34 | public Optional show(@PathVariable String id) { 35 | return productRepository.findById(id); 36 | } 37 | 38 | @RequestMapping(method=RequestMethod.PUT, value="/api/products/{id}") 39 | public Product update(@PathVariable String id, @RequestBody Product product) { 40 | Optional prod = productRepository.findById(id); 41 | if(product.getProdName() != null) 42 | prod.get().setProdName(product.getProdName()); 43 | if(product.getProdDesc() != null) 44 | prod.get().setProdDesc(product.getProdDesc()); 45 | if(product.getProdPrice() != null) 46 | prod.get().setProdPrice(product.getProdPrice()); 47 | if(product.getProdImage() != null) 48 | prod.get().setProdImage(product.getProdImage()); 49 | productRepository.save(prod.get()); 50 | return prod.get(); 51 | } 52 | 53 | @RequestMapping(method=RequestMethod.DELETE, value="/api/products/{id}") 54 | public String delete(@PathVariable String id) { 55 | Optional product = productRepository.findById(id); 56 | productRepository.delete(product.get()); 57 | 58 | return "product deleted"; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/models/Product.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.models; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.mapping.Document; 5 | 6 | @Document(collection = "products") 7 | public class Product { 8 | 9 | @Id 10 | String id; 11 | String prodName; 12 | String prodDesc; 13 | Double prodPrice; 14 | String prodImage; 15 | 16 | public Product() { 17 | } 18 | 19 | public Product(String prodName, String prodDesc, Double prodPrice, String prodImage) { 20 | super(); 21 | this.prodName = prodName; 22 | this.prodDesc = prodDesc; 23 | this.prodPrice = prodPrice; 24 | this.prodImage = prodImage; 25 | } 26 | 27 | public String getId() { 28 | return id; 29 | } 30 | 31 | public void setId(String id) { 32 | this.id = id; 33 | } 34 | 35 | public String getProdName() { 36 | return prodName; 37 | } 38 | 39 | public void setProdName(String prodName) { 40 | this.prodName = prodName; 41 | } 42 | 43 | public String getProdDesc() { 44 | return prodDesc; 45 | } 46 | 47 | public void setProdDesc(String prodDesc) { 48 | this.prodDesc = prodDesc; 49 | } 50 | 51 | public Double getProdPrice() { 52 | return prodPrice; 53 | } 54 | 55 | public void setProdPrice(Double prodPrice) { 56 | this.prodPrice = prodPrice; 57 | } 58 | 59 | public String getProdImage() { 60 | return prodImage; 61 | } 62 | 63 | public void setProdImage(String prodImage) { 64 | this.prodImage = prodImage; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/models/Role.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.models; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.index.IndexDirection; 5 | import org.springframework.data.mongodb.core.index.Indexed; 6 | import org.springframework.data.mongodb.core.mapping.Document; 7 | 8 | @Document(collection = "roles") 9 | public class Role { 10 | 11 | @Id 12 | private String id; 13 | @Indexed(unique = true, direction = IndexDirection.DESCENDING, dropDups = true) 14 | 15 | private String role; 16 | public String getId() { 17 | return id; 18 | } 19 | public void setId(String id) { 20 | this.id = id; 21 | } 22 | public String getRole() { 23 | return role; 24 | } 25 | public void setRole(String role) { 26 | this.role = role; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/models/User.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.models; 2 | 3 | import java.util.Set; 4 | 5 | import org.springframework.data.annotation.Id; 6 | import org.springframework.data.mongodb.core.index.IndexDirection; 7 | import org.springframework.data.mongodb.core.index.Indexed; 8 | import org.springframework.data.mongodb.core.mapping.DBRef; 9 | import org.springframework.data.mongodb.core.mapping.Document; 10 | 11 | @Document(collection = "users") 12 | public class User { 13 | 14 | @Id 15 | private String id; 16 | @Indexed(unique = true, direction = IndexDirection.DESCENDING, dropDups = true) 17 | private String email; 18 | private String password; 19 | private String fullname; 20 | private boolean enabled; 21 | @DBRef 22 | private Set roles; 23 | public String getId() { 24 | return id; 25 | } 26 | public void setId(String id) { 27 | this.id = id; 28 | } 29 | public String getEmail() { 30 | return email; 31 | } 32 | public void setEmail(String email) { 33 | this.email = email; 34 | } 35 | public String getPassword() { 36 | return password; 37 | } 38 | public void setPassword(String password) { 39 | this.password = password; 40 | } 41 | public String getFullname() { 42 | return fullname; 43 | } 44 | public void setFullname(String fullname) { 45 | this.fullname = fullname; 46 | } 47 | public boolean isEnabled() { 48 | return enabled; 49 | } 50 | public void setEnabled(boolean enabled) { 51 | this.enabled = enabled; 52 | } 53 | public Set getRoles() { 54 | return roles; 55 | } 56 | public void setRoles(Set roles) { 57 | this.roles = roles; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/repositories/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.repositories; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | import com.djamware.SecurityRest.models.Product; 6 | 7 | public interface ProductRepository extends CrudRepository { 8 | 9 | @Override 10 | void delete(Product deleted); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/repositories/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.repositories; 2 | 3 | import org.springframework.data.mongodb.repository.MongoRepository; 4 | 5 | import com.djamware.SecurityRest.models.Role; 6 | 7 | public interface RoleRepository extends MongoRepository { 8 | 9 | Role findByRole(String role); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/repositories/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.repositories; 2 | 3 | import org.springframework.data.mongodb.repository.MongoRepository; 4 | 5 | import com.djamware.SecurityRest.models.User; 6 | 7 | public interface UserRepository extends MongoRepository { 8 | 9 | User findByEmail(String email); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/SecurityRest/services/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest.services; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashSet; 6 | import java.util.List; 7 | import java.util.Set; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.core.userdetails.UserDetails; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 15 | import org.springframework.security.crypto.password.PasswordEncoder; 16 | import org.springframework.stereotype.Service; 17 | 18 | import com.djamware.SecurityRest.models.Role; 19 | import com.djamware.SecurityRest.models.User; 20 | import com.djamware.SecurityRest.repositories.RoleRepository; 21 | import com.djamware.SecurityRest.repositories.UserRepository; 22 | 23 | @Service 24 | public class CustomUserDetailsService implements UserDetailsService { 25 | 26 | @Autowired 27 | private UserRepository userRepository; 28 | 29 | @Autowired 30 | private RoleRepository roleRepository; 31 | 32 | @Autowired 33 | private PasswordEncoder bCryptPasswordEncoder; 34 | 35 | public User findUserByEmail(String email) { 36 | return userRepository.findByEmail(email); 37 | } 38 | 39 | public void saveUser(User user) { 40 | user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); 41 | user.setEnabled(true); 42 | Role userRole = roleRepository.findByRole("ADMIN"); 43 | user.setRoles(new HashSet<>(Arrays.asList(userRole))); 44 | userRepository.save(user); 45 | } 46 | 47 | @Override 48 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 49 | 50 | User user = userRepository.findByEmail(email); 51 | if(user != null) { 52 | List authorities = getUserAuthority(user.getRoles()); 53 | return buildUserForAuthentication(user, authorities); 54 | } else { 55 | throw new UsernameNotFoundException("username not found"); 56 | } 57 | } 58 | 59 | private List getUserAuthority(Set userRoles) { 60 | Set roles = new HashSet<>(); 61 | userRoles.forEach((role) -> { 62 | roles.add(new SimpleGrantedAuthority(role.getRole())); 63 | }); 64 | 65 | List grantedAuthorities = new ArrayList<>(roles); 66 | return grantedAuthorities; 67 | } 68 | 69 | private UserDetails buildUserForAuthentication(User user, List authorities) { 70 | return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.database=springmongodb 2 | spring.data.mongodb.host=localhost 3 | spring.data.mongodb.port=27017 -------------------------------------------------------------------------------- /src/test/java/com/djamware/SecurityRest/SecurityRestApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.djamware.SecurityRest; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SecurityRestApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | 18 | --------------------------------------------------------------------------------