├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── customs.json ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── djamware │ │ └── springbootmongodbsecurity │ │ ├── SpringbootMongodbSecurityApplication.java │ │ ├── config │ │ ├── CustomizeAuthenticationSuccessHandler.java │ │ ├── PageConfig.java │ │ └── WebSecurityConfig.java │ │ ├── controller │ │ └── LoginController.java │ │ ├── domain │ │ ├── Role.java │ │ └── User.java │ │ ├── repository │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ └── service │ │ └── CustomUserDetailsService.java └── resources │ ├── application.properties │ ├── static │ └── css │ │ └── style.css │ └── templates │ ├── dashboard.html │ ├── default.html │ ├── home.html │ ├── login.html │ └── signup.html └── test └── java └── com └── djamware └── springbootmongodbsecurity └── SpringbootMongodbSecurityApplicationTests.java /.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 | /build/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 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 | # Spring Boot, Security, and Data MongoDB Authentication Example 2 | 3 | This tutorial is part of [Spring Boot, Security, and Data MongoDB Authentication Example](https://www.djamware.com/post/5b2f000880aca77b083240b2/spring-boot-security-and-data-mongodb-authentication-example) 4 | 5 | To run locally: 6 | 7 | * Clone this repo 8 | * Run MongoDB daemon in the other tab `mongod` 9 | * Build this source `./gradlew build` 10 | * Run this application `./gradlew bootRun` 11 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.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: 'eclipse' 15 | apply plugin: 'org.springframework.boot' 16 | apply plugin: 'io.spring.dependency-management' 17 | 18 | group = 'com.djamware' 19 | version = '0.0.1-SNAPSHOT' 20 | sourceCompatibility = 1.8 21 | 22 | repositories { 23 | mavenCentral() 24 | } 25 | 26 | 27 | dependencies { 28 | compile('org.springframework.boot:spring-boot-starter-data-mongodb') 29 | compile('org.springframework.boot:spring-boot-starter-security') 30 | compile('org.springframework.boot:spring-boot-starter-thymeleaf') 31 | compile('org.springframework.boot:spring-boot-starter-web') 32 | // compile('org.webjars:bootstrap:4.0.0') 33 | compile('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect') 34 | testCompile('org.springframework.boot:spring-boot-starter-test') 35 | testCompile('org.springframework.security:spring-security-test') 36 | } 37 | -------------------------------------------------------------------------------- /customs.json: -------------------------------------------------------------------------------- 1 | { 2 | "elements": {}, 3 | "attributes": { 4 | "layout:decorator": { 5 | "context": "html" 6 | }, 7 | "layout:fragment": {} 8 | } 9 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didinj/springboot-mongodb-security/0a15fff597009276469920ca709f4719c237ac5c/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Feb 06 12:27:20 CET 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip 7 | -------------------------------------------------------------------------------- /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 = 'springboot-mongodb-security' 2 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/SpringbootMongodbSecurityApplication.java: -------------------------------------------------------------------------------- 1 | package com.djamware.springbootmongodbsecurity; 2 | 3 | import com.djamware.springbootmongodbsecurity.domain.Role; 4 | import com.djamware.springbootmongodbsecurity.repository.RoleRepository; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.context.annotation.Bean; 9 | 10 | @SpringBootApplication 11 | public class SpringbootMongodbSecurityApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringbootMongodbSecurityApplication.class, args); 15 | } 16 | 17 | @Bean 18 | CommandLineRunner init(RoleRepository roleRepository) { 19 | 20 | return args -> { 21 | 22 | Role adminRole = roleRepository.findByRole("ADMIN"); 23 | if (adminRole == null) { 24 | Role newAdminRole = new Role(); 25 | newAdminRole.setRole("ADMIN"); 26 | roleRepository.save(newAdminRole); 27 | } 28 | 29 | Role userRole = roleRepository.findByRole("USER"); 30 | if (userRole == null) { 31 | Role newUserRole = new Role(); 32 | newUserRole.setRole("USER"); 33 | roleRepository.save(newUserRole); 34 | } 35 | }; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/config/CustomizeAuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.config; 7 | 8 | import java.io.IOException; 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.GrantedAuthority; 14 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 15 | import org.springframework.stereotype.Component; 16 | 17 | /** 18 | * 19 | * @author didin 20 | */ 21 | @Component 22 | public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler { 23 | 24 | @Override 25 | public void onAuthenticationSuccess(HttpServletRequest request, 26 | HttpServletResponse response, Authentication authentication) 27 | throws IOException, ServletException { 28 | //set our response to OK status 29 | response.setStatus(HttpServletResponse.SC_OK); 30 | 31 | for (GrantedAuthority auth : authentication.getAuthorities()) { 32 | if ("ADMIN".equals(auth.getAuthority())) { 33 | response.sendRedirect("/dashboard"); 34 | } 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/config/PageConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.config; 7 | 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 12 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 13 | 14 | /** 15 | * 16 | * @author didin 17 | */ 18 | @Configuration 19 | public class PageConfig implements WebMvcConfigurer { 20 | 21 | @Bean 22 | public BCryptPasswordEncoder passwordEncoder() { 23 | BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); 24 | return bCryptPasswordEncoder; 25 | } 26 | 27 | @Override 28 | public void addViewControllers(ViewControllerRegistry registry) { 29 | registry.addViewController("/home").setViewName("home"); 30 | registry.addViewController("/").setViewName("home"); 31 | registry.addViewController("/dashboard").setViewName("dashboard"); 32 | registry.addViewController("/login").setViewName("login"); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.config; 7 | 8 | import com.djamware.springbootmongodbsecurity.service.CustomUserDetailsService; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 16 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 19 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 20 | 21 | /** 22 | * 23 | * @author didin 24 | */ 25 | @Configuration 26 | @EnableWebSecurity 27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 28 | 29 | @Autowired 30 | private BCryptPasswordEncoder bCryptPasswordEncoder; 31 | 32 | @Autowired 33 | CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler; 34 | 35 | @Bean 36 | public UserDetailsService mongoUserDetails() { 37 | return new CustomUserDetailsService(); 38 | } 39 | 40 | @Override 41 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 42 | UserDetailsService userDetailsService = mongoUserDetails(); 43 | auth 44 | .userDetailsService(userDetailsService) 45 | .passwordEncoder(bCryptPasswordEncoder); 46 | 47 | } 48 | 49 | @Override 50 | protected void configure(HttpSecurity http) throws Exception { 51 | http 52 | .authorizeRequests() 53 | .antMatchers("/").permitAll() 54 | .antMatchers("/login").permitAll() 55 | .antMatchers("/signup").permitAll() 56 | .antMatchers("/dashboard/**").hasAuthority("ADMIN").anyRequest() 57 | .authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler) 58 | .loginPage("/login").failureUrl("/login?error=true") 59 | .usernameParameter("email") 60 | .passwordParameter("password") 61 | .and().logout() 62 | .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 63 | .logoutSuccessUrl("/").and().exceptionHandling(); 64 | } 65 | 66 | @Override 67 | public void configure(WebSecurity web) throws Exception { 68 | web 69 | .ignoring() 70 | .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**"); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.controller; 7 | 8 | import com.djamware.springbootmongodbsecurity.domain.User; 9 | import com.djamware.springbootmongodbsecurity.service.CustomUserDetailsService; 10 | import javax.validation.Valid; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.stereotype.Controller; 15 | import org.springframework.validation.BindingResult; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.RequestMethod; 18 | import org.springframework.web.servlet.ModelAndView; 19 | 20 | /** 21 | * 22 | * @author didin 23 | */ 24 | @Controller 25 | public class LoginController { 26 | 27 | @Autowired 28 | private CustomUserDetailsService userService; 29 | 30 | @RequestMapping(value = "/login", method = RequestMethod.GET) 31 | public ModelAndView login() { 32 | ModelAndView modelAndView = new ModelAndView(); 33 | modelAndView.setViewName("login"); 34 | return modelAndView; 35 | } 36 | 37 | @RequestMapping(value = "/signup", method = RequestMethod.GET) 38 | public ModelAndView signup() { 39 | ModelAndView modelAndView = new ModelAndView(); 40 | User user = new User(); 41 | modelAndView.addObject("user", user); 42 | modelAndView.setViewName("signup"); 43 | return modelAndView; 44 | } 45 | 46 | @RequestMapping(value = "/signup", method = RequestMethod.POST) 47 | public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) { 48 | ModelAndView modelAndView = new ModelAndView(); 49 | User userExists = userService.findUserByEmail(user.getEmail()); 50 | if (userExists != null) { 51 | bindingResult 52 | .rejectValue("email", "error.user", 53 | "There is already a user registered with the username provided"); 54 | } 55 | if (bindingResult.hasErrors()) { 56 | modelAndView.setViewName("signup"); 57 | } else { 58 | userService.saveUser(user); 59 | modelAndView.addObject("successMessage", "User has been registered successfully"); 60 | modelAndView.addObject("user", new User()); 61 | modelAndView.setViewName("login"); 62 | 63 | } 64 | return modelAndView; 65 | } 66 | 67 | @RequestMapping(value = "/dashboard", method = RequestMethod.GET) 68 | public ModelAndView dashboard() { 69 | ModelAndView modelAndView = new ModelAndView(); 70 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 71 | User user = userService.findUserByEmail(auth.getName()); 72 | modelAndView.addObject("currentUser", user); 73 | modelAndView.addObject("fullName", "Welcome " + user.getFullname()); 74 | modelAndView.addObject("adminMessage", "Content Available Only for Users with Admin Role"); 75 | modelAndView.setViewName("dashboard"); 76 | return modelAndView; 77 | } 78 | 79 | @RequestMapping(value = {"/","/home"}, method = RequestMethod.GET) 80 | public ModelAndView home() { 81 | ModelAndView modelAndView = new ModelAndView(); 82 | modelAndView.setViewName("home"); 83 | return modelAndView; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/domain/Role.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.domain; 7 | 8 | import org.springframework.data.annotation.Id; 9 | import org.springframework.data.mongodb.core.mapping.Document; 10 | import org.springframework.data.mongodb.core.index.IndexDirection; 11 | import org.springframework.data.mongodb.core.index.Indexed; 12 | 13 | /** 14 | * 15 | * @author didin 16 | */ 17 | @Document(collection = "role") 18 | public class Role { 19 | 20 | @Id 21 | private String id; 22 | @Indexed(unique = true, direction = IndexDirection.DESCENDING, dropDups = true) 23 | 24 | private String role; 25 | 26 | public String getId() { 27 | return id; 28 | } 29 | 30 | public void setId(String id) { 31 | this.id = id; 32 | } 33 | 34 | public String getRole() { 35 | return role; 36 | } 37 | 38 | public void setRole(String role) { 39 | this.role = role; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/domain/User.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.domain; 7 | 8 | import java.util.Set; 9 | import org.springframework.data.annotation.Id; 10 | import org.springframework.data.mongodb.core.index.IndexDirection; 11 | import org.springframework.data.mongodb.core.index.Indexed; 12 | import org.springframework.data.mongodb.core.mapping.DBRef; 13 | import org.springframework.data.mongodb.core.mapping.Document; 14 | 15 | /** 16 | * 17 | * @author didin 18 | */ 19 | @Document(collection = "user") 20 | public class User { 21 | 22 | @Id 23 | private String id; 24 | @Indexed(unique = true, direction = IndexDirection.DESCENDING, dropDups = true) 25 | private String email; 26 | private String password; 27 | private String fullname; 28 | private boolean enabled; 29 | @DBRef 30 | private Set roles; 31 | 32 | public String getId() { 33 | return id; 34 | } 35 | 36 | public void setId(String id) { 37 | this.id = id; 38 | } 39 | 40 | public String getEmail() { 41 | return email; 42 | } 43 | 44 | public void setEmail(String email) { 45 | this.email = email; 46 | } 47 | 48 | public String getPassword() { 49 | return password; 50 | } 51 | 52 | public void setPassword(String password) { 53 | this.password = password; 54 | } 55 | 56 | public String getFullname() { 57 | return fullname; 58 | } 59 | 60 | public void setFullname(String fullname) { 61 | this.fullname = fullname; 62 | } 63 | 64 | public boolean isEnabled() { 65 | return enabled; 66 | } 67 | 68 | public void setEnabled(boolean enabled) { 69 | this.enabled = enabled; 70 | } 71 | 72 | public Set getRoles() { 73 | return roles; 74 | } 75 | 76 | public void setRoles(Set roles) { 77 | this.roles = roles; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.repository; 7 | 8 | import com.djamware.springbootmongodbsecurity.domain.Role; 9 | import org.springframework.data.mongodb.repository.MongoRepository; 10 | 11 | /** 12 | * 13 | * @author didin 14 | */ 15 | public interface RoleRepository extends MongoRepository { 16 | 17 | Role findByRole(String role); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.repository; 7 | 8 | import com.djamware.springbootmongodbsecurity.domain.User; 9 | import org.springframework.data.mongodb.repository.MongoRepository; 10 | 11 | /** 12 | * 13 | * @author didin 14 | */ 15 | public interface UserRepository extends MongoRepository { 16 | 17 | User findByEmail(String email); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/djamware/springbootmongodbsecurity/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package com.djamware.springbootmongodbsecurity.service; 7 | 8 | import com.djamware.springbootmongodbsecurity.domain.Role; 9 | import com.djamware.springbootmongodbsecurity.domain.User; 10 | import com.djamware.springbootmongodbsecurity.repository.RoleRepository; 11 | import com.djamware.springbootmongodbsecurity.repository.UserRepository; 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.HashSet; 15 | import java.util.List; 16 | import java.util.Set; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.security.core.GrantedAuthority; 19 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 20 | import org.springframework.security.core.userdetails.UserDetails; 21 | import org.springframework.security.core.userdetails.UserDetailsService; 22 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 23 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 24 | import org.springframework.stereotype.Service; 25 | 26 | /** 27 | * 28 | * @author didin 29 | */ 30 | @Service 31 | public class CustomUserDetailsService implements UserDetailsService { 32 | 33 | @Autowired 34 | private UserRepository userRepository; 35 | @Autowired 36 | private RoleRepository roleRepository; 37 | @Autowired 38 | private BCryptPasswordEncoder bCryptPasswordEncoder; 39 | 40 | public User findUserByEmail(String email) { 41 | return userRepository.findByEmail(email); 42 | } 43 | 44 | public void saveUser(User user) { 45 | user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); 46 | user.setEnabled(true); 47 | Role userRole = roleRepository.findByRole("ADMIN"); 48 | user.setRoles(new HashSet<>(Arrays.asList(userRole))); 49 | userRepository.save(user); 50 | } 51 | 52 | @Override 53 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 54 | 55 | User user = userRepository.findByEmail(email); 56 | if(user != null) { 57 | List authorities = getUserAuthority(user.getRoles()); 58 | return buildUserForAuthentication(user, authorities); 59 | } else { 60 | throw new UsernameNotFoundException("username not found"); 61 | } 62 | } 63 | 64 | private List getUserAuthority(Set userRoles) { 65 | Set roles = new HashSet<>(); 66 | userRoles.forEach((role) -> { 67 | roles.add(new SimpleGrantedAuthority(role.getRole())); 68 | }); 69 | 70 | List grantedAuthorities = new ArrayList<>(roles); 71 | return grantedAuthorities; 72 | } 73 | 74 | private UserDetails buildUserForAuthentication(User user, List authorities) { 75 | return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.data.mongodb.database=springmongodb 2 | spring.data.mongodb.host=localhost 3 | spring.data.mongodb.port=27017 -------------------------------------------------------------------------------- /src/main/resources/static/css/style.css: -------------------------------------------------------------------------------- 1 | /* 2 | To change this license header, choose License Headers in Project Properties. 3 | To change this template file, choose Tools | Templates 4 | and open the template in the editor. 5 | */ 6 | /* 7 | Created on : Jun 21, 2018, 9:26:51 PM 8 | Author : didin 9 | */ 10 | html, 11 | body { 12 | height: 100%; 13 | } 14 | 15 | body { 16 | display: -ms-flexbox; 17 | display: flex; 18 | -ms-flex-align: center; 19 | align-items: center; 20 | padding-top: 40px; 21 | padding-bottom: 40px; 22 | background-color: #f5f5f5; 23 | } 24 | 25 | .form-signin { 26 | width: 100%; 27 | max-width: 330px; 28 | padding: 15px; 29 | margin: auto; 30 | } 31 | .form-signin .checkbox { 32 | font-weight: 400; 33 | } 34 | .form-signin .form-control { 35 | position: relative; 36 | box-sizing: border-box; 37 | height: auto; 38 | padding: 10px; 39 | font-size: 16px; 40 | } 41 | .form-signin .form-control:focus { 42 | z-index: 2; 43 | } 44 | .form-signin input[type="email"] { 45 | margin-bottom: -1px; 46 | border-bottom-right-radius: 0; 47 | border-bottom-left-radius: 0; 48 | } 49 | .form-signin input[type="password"] { 50 | margin-bottom: 10px; 51 | border-top-left-radius: 0; 52 | border-top-right-radius: 0; 53 | } 54 | 55 | .form-signin input[type="text"] { 56 | margin-bottom: 10px; 57 | } -------------------------------------------------------------------------------- /src/main/resources/templates/dashboard.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Dashboard 6 | 7 | 8 |
9 |

Hello [[${#httpServletRequest.remoteUser}]]!

10 |

This is your Admin Dashboard

11 |
12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/templates/default.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | Default 7 | 8 | 9 | 10 | 11 | 12 | 35 | 36 |
37 |
38 |
39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/resources/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Spring Security Example 6 | 7 | 8 |
9 |

Welcome!

10 | 11 |

Click here to see a greeting.

12 |
13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Login 6 | 7 | 8 |
9 | 24 | 27 |
28 | 29 | -------------------------------------------------------------------------------- /src/main/resources/templates/signup.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Signup 6 | 7 | 8 |
9 | 26 | 29 |
30 | 31 | -------------------------------------------------------------------------------- /src/test/java/com/djamware/springbootmongodbsecurity/SpringbootMongodbSecurityApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.djamware.springbootmongodbsecurity; 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 SpringbootMongodbSecurityApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------