├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── javachinna │ │ ├── DemoApplication.java │ │ ├── config │ │ ├── AppConfig.java │ │ ├── SetupDataLoader.java │ │ └── WebSecurityConfig.java │ │ ├── controller │ │ └── PagesController.java │ │ ├── dto │ │ ├── LocalUser.java │ │ ├── SocialProvider.java │ │ └── UserRegistrationForm.java │ │ ├── exception │ │ ├── OAuth2AuthenticationProcessingException.java │ │ └── UserAlreadyExistAuthenticationException.java │ │ ├── handler │ │ ├── CustomAuthenticationFailureHandler.java │ │ └── CustomLogoutSuccessHandler.java │ │ ├── model │ │ ├── Role.java │ │ └── User.java │ │ ├── oauth2 │ │ ├── CustomOAuth2UserService.java │ │ ├── CustomOidcUserService.java │ │ ├── OAuth2AccessTokenResponseConverterWithDefaults.java │ │ └── user │ │ │ ├── FacebookOAuth2UserInfo.java │ │ │ ├── GithubOAuth2UserInfo.java │ │ │ ├── GoogleOAuth2UserInfo.java │ │ │ ├── LinkedinOAuth2UserInfo.java │ │ │ ├── OAuth2UserInfo.java │ │ │ └── OAuth2UserInfoFactory.java │ │ ├── repo │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── service │ │ ├── LocalUserDetailService.java │ │ ├── MessageService.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ │ ├── util │ │ └── GeneralUtils.java │ │ └── validator │ │ ├── PasswordMatches.java │ │ └── PasswordMatchesValidator.java ├── resources │ ├── application.properties │ └── messages_en.properties └── webapp │ ├── WEB-INF │ └── views │ │ └── pages │ │ ├── home.jsp │ │ ├── login.jsp │ │ └── register.jsp │ └── static │ ├── css │ └── style.css │ └── img │ ├── facebook.png │ ├── github.png │ ├── google.png │ └── linkedin.png └── test └── java └── com └── javachinna └── demo └── DemoApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-demo -------------------------------------------------------------------------------- /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 | # https://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 Mingw, 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 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | -------------------------------------------------------------------------------- /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 https://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 set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.8.RELEASE 9 | 10 | 11 | com.javachinna 12 | demo 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Demo project for Spring Boot 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-oauth2-client 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-validation 37 | 38 | 39 | javax.servlet 40 | jstl 41 | 42 | 43 | 44 | 45 | org.apache.tomcat.embed 46 | tomcat-embed-jasper 47 | provided 48 | 49 | 50 | org.springframework.security 51 | spring-security-taglibs 52 | 53 | 54 | 55 | mysql 56 | mysql-connector-java 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-test 61 | test 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-devtools 66 | 67 | 68 | org.webjars 69 | bootstrap 70 | 4.1.1 71 | 72 | 73 | org.webjars 74 | webjars-locator 75 | 0.36 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-configuration-processor 80 | true 81 | 82 | 83 | 84 | 85 | 86 | org.springframework.boot 87 | spring-boot-maven-plugin 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.javachinna; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 7 | import org.springframework.transaction.annotation.EnableTransactionManagement; 8 | 9 | @SpringBootApplication(scanBasePackages = "com.javachinna") 10 | @EnableJpaRepositories 11 | @EnableTransactionManagement 12 | public class DemoApplication extends SpringBootServletInitializer { 13 | 14 | public static void main(String[] args) { 15 | SpringApplicationBuilder app = new SpringApplicationBuilder(DemoApplication.class); 16 | app.run(); 17 | } 18 | 19 | @Override 20 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 21 | return application.sources(DemoApplication.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.context.MessageSource; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 9 | import org.springframework.validation.Validator; 10 | import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 11 | import org.springframework.web.servlet.LocaleResolver; 12 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 13 | import org.springframework.web.servlet.i18n.CookieLocaleResolver; 14 | 15 | @Configuration 16 | public class AppConfig implements WebMvcConfigurer { 17 | 18 | // beans 19 | @Bean 20 | public MessageSource messageSource() { 21 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 22 | messageSource.setBasename("classpath:messages"); 23 | messageSource.setDefaultEncoding("UTF-8"); 24 | return messageSource; 25 | } 26 | 27 | @Bean 28 | public LocaleResolver localeResolver() { 29 | final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 30 | cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); 31 | return cookieLocaleResolver; 32 | } 33 | 34 | @Override 35 | public Validator getValidator() { 36 | LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); 37 | validator.setValidationMessageSource(messageSource()); 38 | return validator; 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/config/SetupDataLoader.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.ApplicationListener; 5 | import org.springframework.context.event.ContextRefreshedEvent; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.javachinna.model.Role; 10 | import com.javachinna.repo.RoleRepository; 11 | 12 | @Component 13 | public class SetupDataLoader implements ApplicationListener { 14 | 15 | private boolean alreadySetup = false; 16 | 17 | @Autowired 18 | private RoleRepository roleRepository; 19 | 20 | @Override 21 | @Transactional 22 | public void onApplicationEvent(final ContextRefreshedEvent event) { 23 | if (alreadySetup) { 24 | return; 25 | } 26 | 27 | // Create initial roles 28 | createRoleIfNotFound(Role.ROLE_USER); 29 | 30 | alreadySetup = true; 31 | } 32 | 33 | @Transactional 34 | private final Role createRoleIfNotFound(final String name) { 35 | Role role = roleRepository.findByName(name); 36 | if (role == null) { 37 | role = new Role(name); 38 | } 39 | role = roleRepository.save(role); 40 | return role; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.config; 2 | 3 | import java.util.Arrays; 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.http.converter.FormHttpMessageConverter; 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.core.userdetails.UserDetailsService; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient; 18 | import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; 19 | import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; 20 | import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler; 21 | import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter; 22 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 23 | import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 24 | import org.springframework.web.client.RestTemplate; 25 | 26 | import com.javachinna.model.Role; 27 | import com.javachinna.oauth2.CustomOAuth2UserService; 28 | import com.javachinna.oauth2.CustomOidcUserService; 29 | import com.javachinna.oauth2.OAuth2AccessTokenResponseConverterWithDefaults; 30 | 31 | @Configuration 32 | @EnableWebSecurity 33 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 34 | 35 | private static final String[] IGNORED_RESOURCE_LIST = new String[] { "/fonts/**", "/webjars/**", "/files/**", "/static/**", "/robots.txt" }; 36 | 37 | @Autowired 38 | private AuthenticationFailureHandler authenticationFailureHandler; 39 | 40 | @Autowired 41 | private LogoutSuccessHandler logoutSuccessHandler; 42 | 43 | @Autowired 44 | private UserDetailsService userDetailsService; 45 | 46 | @Autowired 47 | private CustomOAuth2UserService customOAuth2UserService; 48 | 49 | @Autowired 50 | CustomOidcUserService customOidcUserService; 51 | 52 | @Autowired 53 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 54 | auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 55 | } 56 | 57 | @Override 58 | protected void configure(HttpSecurity http) throws Exception { 59 | 60 | http.csrf().disable(); 61 | 62 | http.authorizeRequests().antMatchers("/", "/home").hasRole(Role.USER); 63 | // Pages do not require login 64 | http.authorizeRequests().antMatchers("/**").permitAll(); 65 | 66 | // Form Login config 67 | http.authorizeRequests().and().formLogin()// 68 | // Submit URL of login page. 69 | // .loginProcessingUrl("/j_spring_security_check") // Submit URL 70 | .loginPage("/login")// 71 | .defaultSuccessUrl("/home")// 72 | .failureUrl("/login?error=true").failureHandler(authenticationFailureHandler)// 73 | .usernameParameter("j_username")// 74 | .passwordParameter("j_password").and().oauth2Login().loginPage("/login").failureHandler(authenticationFailureHandler).defaultSuccessUrl("/home").userInfoEndpoint() 75 | .oidcUserService(customOidcUserService).userService(customOAuth2UserService).and().tokenEndpoint() 76 | .accessTokenResponseClient(authorizationCodeTokenResponseClient()); 77 | // Logout Config 78 | http.authorizeRequests().and().logout().deleteCookies("JSESSIONID").logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); 79 | // 80 | http.sessionManagement().invalidSessionUrl("/login").maximumSessions(1).expiredUrl("/login?session=expired"); 81 | } 82 | 83 | // This bean is load the user specific data when form login is used. 84 | @Override 85 | public UserDetailsService userDetailsService() { 86 | return userDetailsService; 87 | } 88 | 89 | @Bean 90 | public PasswordEncoder passwordEncoder() { 91 | return new BCryptPasswordEncoder(10); 92 | } 93 | 94 | @Override 95 | public void configure(WebSecurity web) throws Exception { 96 | web.ignoring().antMatchers(IGNORED_RESOURCE_LIST); 97 | } 98 | 99 | private OAuth2AccessTokenResponseClient authorizationCodeTokenResponseClient() { 100 | OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); 101 | tokenResponseHttpMessageConverter.setTokenResponseConverter(new OAuth2AccessTokenResponseConverterWithDefaults()); 102 | RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter)); 103 | restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); 104 | DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); 105 | tokenResponseClient.setRestOperations(restTemplate); 106 | return tokenResponseClient; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/controller/PagesController.java: -------------------------------------------------------------------------------- 1 | 2 | package com.javachinna.controller; 3 | 4 | import java.io.IOException; 5 | 6 | import javax.annotation.Resource; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import javax.validation.Valid; 11 | 12 | import org.apache.logging.log4j.LogManager; 13 | import org.apache.logging.log4j.Logger; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.validation.BindingResult; 16 | import org.springframework.web.bind.annotation.GetMapping; 17 | import org.springframework.web.bind.annotation.PostMapping; 18 | import org.springframework.web.bind.annotation.RequestParam; 19 | import org.springframework.web.bind.annotation.RestController; 20 | import org.springframework.web.servlet.ModelAndView; 21 | import org.springframework.web.servlet.mvc.support.RedirectAttributes; 22 | 23 | import com.javachinna.dto.UserRegistrationForm; 24 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 25 | import com.javachinna.service.MessageService; 26 | import com.javachinna.service.UserService; 27 | 28 | /** 29 | * 30 | * @author Chinna 31 | * 32 | */ 33 | @RestController 34 | public class PagesController { 35 | 36 | private final Logger logger = LogManager.getLogger(getClass()); 37 | 38 | @Resource 39 | private MessageService messageService; 40 | 41 | @Autowired 42 | private UserService userService; 43 | 44 | @GetMapping("/login") 45 | public ModelAndView login(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "error", required = false) String error, 46 | @RequestParam(value = "logout", required = false) String logout, @RequestParam(value = "errorCode", required = false) String errorCode) 47 | throws ServletException, IOException { 48 | ModelAndView model = new ModelAndView(); 49 | if (error != null) { 50 | model.addObject("css", "danger"); 51 | model.addObject("msg", error); 52 | } else if (logout != null) { 53 | model.addObject("css", "success"); 54 | model.addObject("msg", messageService.getMessage("message.logout." + logout)); 55 | } 56 | model.addObject("title", "Login Page"); 57 | model.setViewName("login"); 58 | return model; 59 | } 60 | 61 | @GetMapping("/register") 62 | public ModelAndView register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 63 | return new ModelAndView("register", "userRegistrationForm", new UserRegistrationForm()); 64 | } 65 | 66 | @PostMapping("/register") 67 | public ModelAndView registerUser(@Valid UserRegistrationForm userRegistrationForm, BindingResult result, final HttpServletRequest request, RedirectAttributes attributes) { 68 | ModelAndView model = new ModelAndView("register"); 69 | if (!result.hasErrors()) { 70 | try { 71 | userService.registerNewUser(userRegistrationForm); 72 | attributes.addFlashAttribute("css", "success"); 73 | attributes.addFlashAttribute("msg", messageService.getMessage("message.regSucc")); 74 | model = new ModelAndView("redirect:/login"); 75 | } catch (UserAlreadyExistAuthenticationException e) { 76 | logger.error(e); 77 | result.rejectValue("email", "message.regError"); 78 | } 79 | } 80 | return model; 81 | } 82 | 83 | @GetMapping({ "/", "/home" }) 84 | public ModelAndView home(@RequestParam(value = "view", required = false) String view) { 85 | logger.info("Entering home page"); 86 | ModelAndView model = new ModelAndView("home"); 87 | model.addObject("title", "Home"); 88 | model.addObject("view", view); 89 | return model; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/dto/LocalUser.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.userdetails.User; 8 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 9 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 10 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 11 | import org.springframework.security.oauth2.core.user.OAuth2User; 12 | 13 | import com.javachinna.util.GeneralUtils; 14 | 15 | /** 16 | * 17 | * @author Chinna 18 | * 19 | */ 20 | public class LocalUser extends User implements OAuth2User, OidcUser { 21 | 22 | /** 23 | * 24 | */ 25 | private static final long serialVersionUID = -2845160792248762779L; 26 | private final OidcIdToken idToken; 27 | private final OidcUserInfo userInfo; 28 | private Map attributes; 29 | private com.javachinna.model.User user; 30 | 31 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 32 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user) { 33 | this(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, user, null, null); 34 | } 35 | 36 | public LocalUser(final String userID, final String password, final boolean enabled, final boolean accountNonExpired, final boolean credentialsNonExpired, 37 | final boolean accountNonLocked, final Collection authorities, final com.javachinna.model.User user, OidcIdToken idToken, 38 | OidcUserInfo userInfo) { 39 | super(userID, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 40 | this.user = user; 41 | this.idToken = idToken; 42 | this.userInfo = userInfo; 43 | } 44 | 45 | public static LocalUser create(com.javachinna.model.User user, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 46 | LocalUser localUser = new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), 47 | user, idToken, userInfo); 48 | localUser.setAttributes(attributes); 49 | return localUser; 50 | } 51 | 52 | public void setAttributes(Map attributes) { 53 | this.attributes = attributes; 54 | } 55 | 56 | @Override 57 | public String getName() { 58 | return this.user.getDisplayName(); 59 | } 60 | 61 | @Override 62 | public Map getAttributes() { 63 | return this.attributes; 64 | } 65 | 66 | @Override 67 | public Map getClaims() { 68 | return this.attributes; 69 | } 70 | 71 | @Override 72 | public OidcUserInfo getUserInfo() { 73 | return this.userInfo; 74 | } 75 | 76 | @Override 77 | public OidcIdToken getIdToken() { 78 | return this.idToken; 79 | } 80 | 81 | public com.javachinna.model.User getUser() { 82 | return user; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/dto/SocialProvider.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | /** 4 | * @author Chinna 5 | * @since 26/3/18 6 | */ 7 | public enum SocialProvider { 8 | 9 | FACEBOOK("facebook"), TWITTER("twitter"), LINKEDIN("linkedin"), GOOGLE("google"), GITHUB("github"), LOCAL("local"); 10 | 11 | private String providerType; 12 | 13 | public String getProviderType() { 14 | return providerType; 15 | } 16 | 17 | SocialProvider(final String providerType) { 18 | this.providerType = providerType; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/dto/UserRegistrationForm.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.dto; 2 | 3 | import javax.validation.constraints.NotEmpty; 4 | import javax.validation.constraints.Size; 5 | 6 | import com.javachinna.validator.PasswordMatches; 7 | 8 | /** 9 | * @author Chinna 10 | * @since 26/3/18 11 | */ 12 | @PasswordMatches 13 | public class UserRegistrationForm { 14 | 15 | private Long userID; 16 | 17 | private String providerUserId; 18 | 19 | @NotEmpty 20 | private String displayName; 21 | 22 | @NotEmpty 23 | private String email; 24 | 25 | private SocialProvider socialProvider; 26 | 27 | @Size(min = 8, message = "{Size.userDto.password}") 28 | private String password; 29 | 30 | @NotEmpty 31 | private String matchingPassword; 32 | 33 | public UserRegistrationForm() { 34 | } 35 | 36 | /** 37 | * @param userID 38 | * @param displayName 39 | * @param firstName 40 | * @param lastName 41 | * @param phoneno 42 | * @param email 43 | * @param password 44 | * @param socialProvider 45 | */ 46 | public UserRegistrationForm(String providerUserId, String displayName, String email, String password, SocialProvider socialProvider) { 47 | this.providerUserId = providerUserId; 48 | this.displayName = displayName; 49 | this.email = email; 50 | this.password = password; 51 | this.socialProvider = socialProvider; 52 | } 53 | 54 | public static Builder getBuilder() { 55 | return new Builder(); 56 | } 57 | 58 | public String getEmail() { 59 | return email; 60 | } 61 | 62 | public void setEmail(final String email) { 63 | this.email = email; 64 | } 65 | 66 | public String getPassword() { 67 | return password; 68 | } 69 | 70 | public void setPassword(final String password) { 71 | this.password = password; 72 | } 73 | 74 | public SocialProvider getSocialProvider() { 75 | return socialProvider; 76 | } 77 | 78 | public void setSocialProvider(final SocialProvider socialProvider) { 79 | this.socialProvider = socialProvider; 80 | } 81 | 82 | public Long getUserID() { 83 | return userID; 84 | } 85 | 86 | public void setUserID(Long userID) { 87 | this.userID = userID; 88 | } 89 | 90 | public String getDisplayName() { 91 | return displayName; 92 | } 93 | 94 | public void setDisplayName(String displayName) { 95 | this.displayName = displayName; 96 | } 97 | 98 | public String getProviderUserId() { 99 | return providerUserId; 100 | } 101 | 102 | public void setProviderUserId(String providerUserId) { 103 | this.providerUserId = providerUserId; 104 | } 105 | 106 | public String getMatchingPassword() { 107 | return matchingPassword; 108 | } 109 | 110 | public void setMatchingPassword(String matchingPassword) { 111 | this.matchingPassword = matchingPassword; 112 | } 113 | 114 | public static class Builder { 115 | private String providerUserID; 116 | private String displayName; 117 | private String email; 118 | private String password; 119 | private SocialProvider socialProvider; 120 | 121 | public Builder addProviderUserID(final String userID) { 122 | this.providerUserID = userID; 123 | return this; 124 | } 125 | 126 | public Builder addDisplayName(final String displayName) { 127 | this.displayName = displayName; 128 | return this; 129 | } 130 | 131 | public Builder addEmail(final String email) { 132 | this.email = email; 133 | return this; 134 | } 135 | 136 | public Builder addPassword(final String password) { 137 | this.password = password; 138 | return this; 139 | } 140 | 141 | public Builder addSocialProvider(final SocialProvider socialProvider) { 142 | this.socialProvider = socialProvider; 143 | return this; 144 | } 145 | 146 | public UserRegistrationForm build() { 147 | return new UserRegistrationForm(providerUserID, displayName, email, password, socialProvider); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/exception/OAuth2AuthenticationProcessingException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | public class OAuth2AuthenticationProcessingException extends AuthenticationException { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 3392450042101522832L; 10 | 11 | public OAuth2AuthenticationProcessingException(String msg, Throwable t) { 12 | super(msg, t); 13 | } 14 | 15 | public OAuth2AuthenticationProcessingException(String msg) { 16 | super(msg); 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/exception/UserAlreadyExistAuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | /** 6 | * 7 | * @author Chinna 8 | * 9 | */ 10 | public class UserAlreadyExistAuthenticationException extends AuthenticationException { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 5570981880007077317L; 16 | 17 | public UserAlreadyExistAuthenticationException(final String msg) { 18 | super(msg); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/handler/CustomAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.handler; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.annotation.Resource; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 12 | import org.springframework.stereotype.Component; 13 | 14 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 15 | import com.javachinna.service.MessageService; 16 | 17 | @Component("authenticationFailureHandler") 18 | public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 19 | 20 | @Resource 21 | private MessageService messageService; 22 | 23 | @Override 24 | public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) 25 | throws IOException, ServletException { 26 | String msg = messageService.getMessage("message.badCredentials"); 27 | if (exception instanceof OAuth2AuthenticationProcessingException) { 28 | msg = exception.getMessage() == null ? "OAuth error occurred" : exception.getMessage(); 29 | } 30 | setDefaultFailureUrl("/login?error=" + msg); 31 | super.onAuthenticationFailure(request, response, exception); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/handler/CustomLogoutSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.handler; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; 11 | import org.springframework.stereotype.Component; 12 | 13 | @Component("logoutSuccessHandler") 14 | public class CustomLogoutSuccessHandler implements LogoutSuccessHandler { 15 | 16 | @Override 17 | public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { 18 | response.sendRedirect("/login?logout=success"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Set; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.Id; 9 | import javax.persistence.ManyToMany; 10 | import javax.persistence.NamedQuery; 11 | 12 | /** 13 | * The persistent class for the role database table. 14 | * 15 | */ 16 | @Entity 17 | @NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r") 18 | public class Role implements Serializable { 19 | private static final long serialVersionUID = 1L; 20 | public static final String USER = "USER"; 21 | public static final String ROLE_USER = "ROLE_USER"; 22 | 23 | @Id 24 | @Column(name = "ROLE_ID") 25 | private int roleId; 26 | 27 | private String name; 28 | 29 | // bi-directional many-to-many association to User 30 | @ManyToMany(mappedBy = "roles") 31 | private Set users; 32 | 33 | public Role() { 34 | } 35 | 36 | public Role(String name) { 37 | this.name = name; 38 | } 39 | 40 | public int getRoleId() { 41 | return this.roleId; 42 | } 43 | 44 | public void setRoleId(int roleId) { 45 | this.roleId = roleId; 46 | } 47 | 48 | public String getName() { 49 | return this.name; 50 | } 51 | 52 | public void setName(String name) { 53 | this.name = name; 54 | } 55 | 56 | public Set getUsers() { 57 | return this.users; 58 | } 59 | 60 | public void setUsers(Set users) { 61 | this.users = users; 62 | } 63 | 64 | @Override 65 | public int hashCode() { 66 | final int prime = 31; 67 | int result = 1; 68 | result = prime * result + ((name == null) ? 0 : name.hashCode()); 69 | return result; 70 | } 71 | 72 | @Override 73 | public boolean equals(final Object obj) { 74 | if (this == obj) { 75 | return true; 76 | } 77 | if (obj == null) { 78 | return false; 79 | } 80 | if (getClass() != obj.getClass()) { 81 | return false; 82 | } 83 | final Role role = (Role) obj; 84 | if (!role.equals(role.name)) { 85 | return false; 86 | } 87 | return true; 88 | } 89 | 90 | @Override 91 | public String toString() { 92 | final StringBuilder builder = new StringBuilder(); 93 | builder.append("Role [name=").append(name).append("]").append("[id=").append(roleId).append("]"); 94 | return builder.toString(); 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/model/User.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.Set; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.JoinColumn; 13 | import javax.persistence.JoinTable; 14 | import javax.persistence.ManyToMany; 15 | import javax.persistence.Temporal; 16 | import javax.persistence.TemporalType; 17 | 18 | import com.fasterxml.jackson.annotation.JsonIgnore; 19 | 20 | /** 21 | * The persistent class for the user database table. 22 | * 23 | */ 24 | @Entity 25 | public class User implements Serializable { 26 | 27 | /** 28 | * 29 | */ 30 | private static final long serialVersionUID = 65981149772133526L; 31 | 32 | @Id 33 | @GeneratedValue(strategy = GenerationType.IDENTITY) 34 | @Column(name = "USER_ID") 35 | private Long id; 36 | 37 | @Column(name = "PROVIDER_USER_ID") 38 | private String providerUserId; 39 | 40 | private String email; 41 | 42 | @Column(name = "enabled", columnDefinition = "BIT", length = 1) 43 | private boolean enabled; 44 | 45 | @Column(name = "DISPLAY_NAME") 46 | private String displayName; 47 | 48 | @Column(name = "created_date", nullable = false, updatable = false) 49 | @Temporal(TemporalType.TIMESTAMP) 50 | protected Date createdDate; 51 | 52 | @Temporal(TemporalType.TIMESTAMP) 53 | protected Date modifiedDate; 54 | 55 | private String password; 56 | 57 | private String provider; 58 | 59 | // bi-directional many-to-many association to Role 60 | @JsonIgnore 61 | @ManyToMany 62 | @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") }) 63 | private Set roles; 64 | 65 | public User() { 66 | this.enabled = false; 67 | } 68 | 69 | public Long getId() { 70 | return id; 71 | } 72 | 73 | public void setId(Long id) { 74 | this.id = id; 75 | } 76 | 77 | public String getProviderUserId() { 78 | return providerUserId; 79 | } 80 | 81 | public void setProviderUserId(String providerUserId) { 82 | this.providerUserId = providerUserId; 83 | } 84 | 85 | public String getEmail() { 86 | return email; 87 | } 88 | 89 | public void setEmail(String email) { 90 | this.email = email; 91 | } 92 | 93 | public boolean isEnabled() { 94 | return enabled; 95 | } 96 | 97 | public void setEnabled(boolean enabled) { 98 | this.enabled = enabled; 99 | } 100 | 101 | public String getDisplayName() { 102 | return displayName; 103 | } 104 | 105 | public void setDisplayName(String displayName) { 106 | this.displayName = displayName; 107 | } 108 | 109 | public Date getCreatedDate() { 110 | return createdDate; 111 | } 112 | 113 | public void setCreatedDate(Date createdDate) { 114 | this.createdDate = createdDate; 115 | } 116 | 117 | public Date getModifiedDate() { 118 | return modifiedDate; 119 | } 120 | 121 | public void setModifiedDate(Date modifiedDate) { 122 | this.modifiedDate = modifiedDate; 123 | } 124 | 125 | public String getPassword() { 126 | return password; 127 | } 128 | 129 | public void setPassword(String password) { 130 | this.password = password; 131 | } 132 | 133 | public String getProvider() { 134 | return provider; 135 | } 136 | 137 | public void setProvider(String provider) { 138 | this.provider = provider; 139 | } 140 | 141 | public Set getRoles() { 142 | return roles; 143 | } 144 | 145 | public void setRoles(Set roles) { 146 | this.roles = roles; 147 | } 148 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/CustomOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.core.env.Environment; 9 | import org.springframework.http.HttpEntity; 10 | import org.springframework.http.HttpHeaders; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; 15 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 16 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 17 | import org.springframework.security.oauth2.core.user.OAuth2User; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.util.Assert; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import com.javachinna.dto.SocialProvider; 23 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 24 | import com.javachinna.service.UserService; 25 | 26 | @Service 27 | public class CustomOAuth2UserService extends DefaultOAuth2UserService { 28 | 29 | @Autowired 30 | private UserService userService; 31 | 32 | @Autowired 33 | private Environment env; 34 | 35 | @Override 36 | public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { 37 | OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); 38 | try { 39 | Map attributes = new HashMap<>(oAuth2User.getAttributes()); 40 | String provider = oAuth2UserRequest.getClientRegistration().getRegistrationId(); 41 | if (provider.equals(SocialProvider.LINKEDIN.getProviderType())) { 42 | populateEmailAddressFromLinkedIn(oAuth2UserRequest, attributes); 43 | } 44 | return userService.processUserRegistration(provider, attributes, null, null); 45 | } catch (AuthenticationException ex) { 46 | throw ex; 47 | } catch (Exception ex) { 48 | ex.printStackTrace(); 49 | // Throwing an instance of AuthenticationException will trigger the 50 | // OAuth2AuthenticationFailureHandler 51 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 52 | } 53 | } 54 | 55 | @SuppressWarnings({ "rawtypes", "unchecked" }) 56 | public void populateEmailAddressFromLinkedIn(OAuth2UserRequest oAuth2UserRequest, Map attributes) throws OAuth2AuthenticationException { 57 | String emailEndpointUri = env.getProperty("linkedin.email-address-uri"); 58 | Assert.notNull(emailEndpointUri, "LinkedIn email address end point required"); 59 | RestTemplate restTemplate = new RestTemplate(); 60 | HttpHeaders headers = new HttpHeaders(); 61 | headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2UserRequest.getAccessToken().getTokenValue()); 62 | HttpEntity entity = new HttpEntity<>("", headers); 63 | ResponseEntity response = restTemplate.exchange(emailEndpointUri, HttpMethod.GET, entity, Map.class); 64 | List list = (List) response.getBody().get("elements"); 65 | Map map = (Map) ((Map) list.get(0)).get("handle~"); 66 | attributes.putAll(map); 67 | } 68 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/CustomOidcUserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.AuthenticationException; 5 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; 6 | import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; 7 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 8 | import org.springframework.security.oauth2.core.oidc.user.OidcUser; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 12 | import com.javachinna.service.UserService; 13 | 14 | @Service 15 | public class CustomOidcUserService extends OidcUserService { 16 | 17 | @Autowired 18 | private UserService userService; 19 | 20 | @Override 21 | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { 22 | OidcUser oidcUser = super.loadUser(userRequest); 23 | try { 24 | return userService.processUserRegistration(userRequest.getClientRegistration().getRegistrationId(), oidcUser.getAttributes(), oidcUser.getIdToken(), 25 | oidcUser.getUserInfo()); 26 | } catch (AuthenticationException ex) { 27 | throw ex; 28 | } catch (Exception ex) { 29 | ex.printStackTrace(); 30 | // Throwing an instance of AuthenticationException will trigger the 31 | // OAuth2AuthenticationFailureHandler 32 | throw new OAuth2AuthenticationProcessingException(ex.getMessage(), ex.getCause()); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/OAuth2AccessTokenResponseConverterWithDefaults.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.LinkedHashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.stream.Collectors; 9 | import java.util.stream.Stream; 10 | 11 | import org.springframework.core.convert.converter.Converter; 12 | import org.springframework.security.oauth2.core.OAuth2AccessToken; 13 | import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; 14 | import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; 15 | import org.springframework.util.Assert; 16 | import org.springframework.util.StringUtils; 17 | 18 | /** 19 | * @author Joe Grandja 20 | */ 21 | public class OAuth2AccessTokenResponseConverterWithDefaults implements Converter, OAuth2AccessTokenResponse> { 22 | private static final Set TOKEN_RESPONSE_PARAMETER_NAMES = Stream 23 | .of(OAuth2ParameterNames.ACCESS_TOKEN, OAuth2ParameterNames.TOKEN_TYPE, OAuth2ParameterNames.EXPIRES_IN, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ParameterNames.SCOPE) 24 | .collect(Collectors.toSet()); 25 | 26 | private OAuth2AccessToken.TokenType defaultAccessTokenType = OAuth2AccessToken.TokenType.BEARER; 27 | 28 | @Override 29 | public OAuth2AccessTokenResponse convert(Map tokenResponseParameters) { 30 | String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN); 31 | 32 | OAuth2AccessToken.TokenType accessTokenType = this.defaultAccessTokenType; 33 | if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) { 34 | accessTokenType = OAuth2AccessToken.TokenType.BEARER; 35 | } 36 | 37 | long expiresIn = 0; 38 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) { 39 | try { 40 | expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN)); 41 | } catch (NumberFormatException ex) { 42 | } 43 | } 44 | 45 | Set scopes = Collections.emptySet(); 46 | if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { 47 | String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE); 48 | scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet()); 49 | } 50 | 51 | Map additionalParameters = new LinkedHashMap<>(); 52 | tokenResponseParameters.entrySet().stream().filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey())) 53 | .forEach(e -> additionalParameters.put(e.getKey(), e.getValue())); 54 | 55 | return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).additionalParameters(additionalParameters).build(); 56 | } 57 | 58 | public final void setDefaultAccessTokenType(OAuth2AccessToken.TokenType defaultAccessTokenType) { 59 | Assert.notNull(defaultAccessTokenType, "defaultAccessTokenType cannot be null"); 60 | this.defaultAccessTokenType = defaultAccessTokenType; 61 | } 62 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/FacebookOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class FacebookOAuth2UserInfo extends OAuth2UserInfo { 6 | public FacebookOAuth2UserInfo(Map attributes) { 7 | super(attributes); 8 | } 9 | 10 | @Override 11 | public String getId() { 12 | return (String) attributes.get("id"); 13 | } 14 | 15 | @Override 16 | public String getName() { 17 | return (String) attributes.get("name"); 18 | } 19 | 20 | @Override 21 | public String getEmail() { 22 | return (String) attributes.get("email"); 23 | } 24 | 25 | @Override 26 | @SuppressWarnings("unchecked") 27 | public String getImageUrl() { 28 | if (attributes.containsKey("picture")) { 29 | Map pictureObj = (Map) attributes.get("picture"); 30 | if (pictureObj.containsKey("data")) { 31 | Map dataObj = (Map) pictureObj.get("data"); 32 | if (dataObj.containsKey("url")) { 33 | return (String) dataObj.get("url"); 34 | } 35 | } 36 | } 37 | return null; 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/GithubOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GithubOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GithubOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return ((Integer) attributes.get("id")).toString(); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("avatar_url"); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/GoogleOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class GoogleOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GoogleOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("sub"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("email"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("picture"); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/LinkedinOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public class LinkedinOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public LinkedinOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("id"); 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return ((String) attributes.get("localizedFirstName")).concat(" ").concat((String) attributes.get("localizedLastName")); 19 | } 20 | 21 | @Override 22 | public String getEmail() { 23 | return (String) attributes.get("emailAddress"); 24 | } 25 | 26 | @Override 27 | public String getImageUrl() { 28 | return (String) attributes.get("pictureUrl"); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/OAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | public abstract class OAuth2UserInfo { 6 | protected Map attributes; 7 | 8 | public OAuth2UserInfo(Map attributes) { 9 | this.attributes = attributes; 10 | } 11 | 12 | public Map getAttributes() { 13 | return attributes; 14 | } 15 | 16 | public abstract String getId(); 17 | 18 | public abstract String getName(); 19 | 20 | public abstract String getEmail(); 21 | 22 | public abstract String getImageUrl(); 23 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/oauth2/user/OAuth2UserInfoFactory.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.oauth2.user; 2 | 3 | import java.util.Map; 4 | 5 | import com.javachinna.dto.SocialProvider; 6 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 7 | 8 | public class OAuth2UserInfoFactory { 9 | public static OAuth2UserInfo getOAuth2UserInfo(String registrationId, Map attributes) { 10 | if (registrationId.equalsIgnoreCase(SocialProvider.GOOGLE.getProviderType())) { 11 | return new GoogleOAuth2UserInfo(attributes); 12 | } else if (registrationId.equalsIgnoreCase(SocialProvider.FACEBOOK.getProviderType())) { 13 | return new FacebookOAuth2UserInfo(attributes); 14 | } else if (registrationId.equalsIgnoreCase(SocialProvider.GITHUB.getProviderType())) { 15 | return new GithubOAuth2UserInfo(attributes); 16 | } else if (registrationId.equalsIgnoreCase(SocialProvider.LINKEDIN.getProviderType())) { 17 | return new LinkedinOAuth2UserInfo(attributes); 18 | } else if (registrationId.equalsIgnoreCase(SocialProvider.TWITTER.getProviderType())) { 19 | return new GithubOAuth2UserInfo(attributes); 20 | } else { 21 | throw new OAuth2AuthenticationProcessingException("Sorry! Login with " + registrationId + " is not supported yet."); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/javachinna/repo/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.Role; 7 | 8 | @Repository 9 | public interface RoleRepository extends JpaRepository { 10 | 11 | Role findByName(String name); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/repo/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.repo; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.javachinna.model.User; 7 | 8 | @Repository 9 | public interface UserRepository extends JpaRepository { 10 | 11 | User findByEmail(String email); 12 | 13 | boolean existsByEmail(String email); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/service/LocalUserDetailService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.javachinna.dto.LocalUser; 10 | import com.javachinna.model.User; 11 | import com.javachinna.util.GeneralUtils; 12 | 13 | /** 14 | * 15 | * @author Chinna 16 | * 17 | */ 18 | @Service("localUserDetailService") 19 | public class LocalUserDetailService implements UserDetailsService { 20 | @Autowired 21 | private UserService userService; 22 | 23 | @Override 24 | @Transactional 25 | public LocalUser loadUserByUsername(final String email) throws UsernameNotFoundException { 26 | User user = userService.findUserByEmail(email); 27 | if (user == null) { 28 | throw new UsernameNotFoundException("User " + email + " was not found in the database"); 29 | } 30 | return new LocalUser(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, GeneralUtils.buildSimpleGrantedAuthorities(user.getRoles()), user); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/service/MessageService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Locale; 4 | 5 | import javax.annotation.Resource; 6 | 7 | import org.springframework.context.MessageSource; 8 | import org.springframework.context.i18n.LocaleContextHolder; 9 | import org.springframework.core.env.Environment; 10 | import org.springframework.stereotype.Component; 11 | 12 | @Component 13 | public class MessageService { 14 | 15 | @Resource 16 | private MessageSource messageSource; 17 | 18 | private Locale locale = LocaleContextHolder.getLocale(); 19 | 20 | public MessageService(Environment environment) { 21 | } 22 | 23 | public String getMessage(String code) { 24 | return messageSource.getMessage(code, null, locale); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 6 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 7 | 8 | import com.javachinna.dto.LocalUser; 9 | import com.javachinna.dto.UserRegistrationForm; 10 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 11 | import com.javachinna.model.User; 12 | 13 | /** 14 | * @author Chinna 15 | * @since 26/3/18 16 | */ 17 | public interface UserService { 18 | 19 | public User registerNewUser(UserRegistrationForm UserRegistrationForm) throws UserAlreadyExistAuthenticationException; 20 | 21 | User findUserByEmail(String email); 22 | 23 | LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.service; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Qualifier; 10 | import org.springframework.security.core.userdetails.UserDetailsService; 11 | import org.springframework.security.crypto.password.PasswordEncoder; 12 | import org.springframework.security.oauth2.core.oidc.OidcIdToken; 13 | import org.springframework.security.oauth2.core.oidc.OidcUserInfo; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | import org.springframework.util.StringUtils; 17 | 18 | import com.javachinna.dto.LocalUser; 19 | import com.javachinna.dto.SocialProvider; 20 | import com.javachinna.dto.UserRegistrationForm; 21 | import com.javachinna.exception.OAuth2AuthenticationProcessingException; 22 | import com.javachinna.exception.UserAlreadyExistAuthenticationException; 23 | import com.javachinna.model.Role; 24 | import com.javachinna.model.User; 25 | import com.javachinna.oauth2.user.OAuth2UserInfo; 26 | import com.javachinna.oauth2.user.OAuth2UserInfoFactory; 27 | import com.javachinna.repo.RoleRepository; 28 | import com.javachinna.repo.UserRepository; 29 | import com.javachinna.util.GeneralUtils; 30 | 31 | /** 32 | * @author Chinna 33 | * @since 26/3/18 34 | */ 35 | @Service 36 | public class UserServiceImpl implements UserService { 37 | 38 | @Autowired 39 | @Qualifier(value = "localUserDetailService") 40 | private UserDetailsService userDetailService; 41 | 42 | @Autowired 43 | private UserRepository userRepository; 44 | 45 | @Autowired 46 | private RoleRepository roleRepository; 47 | 48 | @Autowired 49 | private PasswordEncoder passwordEncoder; 50 | 51 | @Override 52 | @Transactional(value = "transactionManager") 53 | public User registerNewUser(final UserRegistrationForm userRegistrationForm) throws UserAlreadyExistAuthenticationException { 54 | if (userRegistrationForm.getUserID() != null && userRepository.existsById(userRegistrationForm.getUserID())) { 55 | throw new UserAlreadyExistAuthenticationException("User with User id " + userRegistrationForm.getUserID() + " already exist"); 56 | } else if (userRepository.existsByEmail(userRegistrationForm.getEmail())) { 57 | throw new UserAlreadyExistAuthenticationException("User with email id " + userRegistrationForm.getEmail() + " already exist"); 58 | } 59 | User user = buildUser(userRegistrationForm); 60 | Date now = Calendar.getInstance().getTime(); 61 | user.setCreatedDate(now); 62 | user.setModifiedDate(now); 63 | user = userRepository.save(user); 64 | userRepository.flush(); 65 | return user; 66 | } 67 | 68 | private User buildUser(final UserRegistrationForm formDTO) { 69 | User user = new User(); 70 | user.setDisplayName(formDTO.getDisplayName()); 71 | user.setEmail(formDTO.getEmail()); 72 | user.setPassword(passwordEncoder.encode(formDTO.getPassword())); 73 | final HashSet roles = new HashSet(); 74 | roles.add(roleRepository.findByName(Role.ROLE_USER)); 75 | user.setRoles(roles); 76 | user.setProvider(formDTO.getSocialProvider().getProviderType()); 77 | user.setEnabled(true); 78 | user.setProviderUserId(formDTO.getProviderUserId()); 79 | return user; 80 | } 81 | 82 | @Override 83 | public User findUserByEmail(final String email) { 84 | return userRepository.findByEmail(email); 85 | } 86 | 87 | @Override 88 | @Transactional 89 | public LocalUser processUserRegistration(String registrationId, Map attributes, OidcIdToken idToken, OidcUserInfo userInfo) { 90 | OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(registrationId, attributes); 91 | if (StringUtils.isEmpty(oAuth2UserInfo.getName())) { 92 | throw new OAuth2AuthenticationProcessingException("Name not found from OAuth2 provider"); 93 | } else if (StringUtils.isEmpty(oAuth2UserInfo.getEmail())) { 94 | throw new OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider"); 95 | } 96 | UserRegistrationForm userDetails = toUserRegistrationObject(registrationId, oAuth2UserInfo); 97 | User user = findUserByEmail(oAuth2UserInfo.getEmail()); 98 | if (user != null) { 99 | if (!user.getProvider().equals(registrationId) && !user.getProvider().equals(SocialProvider.LOCAL.getProviderType())) { 100 | throw new OAuth2AuthenticationProcessingException( 101 | "Looks like you're signed up with " + user.getProvider() + " account. Please use your " + user.getProvider() + " account to login."); 102 | } 103 | user = updateExistingUser(user, oAuth2UserInfo); 104 | } else { 105 | user = registerNewUser(userDetails); 106 | } 107 | 108 | return LocalUser.create(user, attributes, idToken, userInfo); 109 | } 110 | 111 | private User updateExistingUser(User existingUser, OAuth2UserInfo oAuth2UserInfo) { 112 | existingUser.setDisplayName(oAuth2UserInfo.getName()); 113 | return userRepository.save(existingUser); 114 | } 115 | 116 | private UserRegistrationForm toUserRegistrationObject(String registrationId, OAuth2UserInfo oAuth2UserInfo) { 117 | return UserRegistrationForm.getBuilder().addProviderUserID(oAuth2UserInfo.getId()).addDisplayName(oAuth2UserInfo.getName()).addEmail(oAuth2UserInfo.getEmail()) 118 | .addSocialProvider(GeneralUtils.toSocialProvider(registrationId)).addPassword("changeit").build(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/util/GeneralUtils.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | 9 | import com.javachinna.dto.SocialProvider; 10 | import com.javachinna.model.Role; 11 | 12 | /** 13 | * 14 | * @author Chinna 15 | * 16 | */ 17 | public class GeneralUtils { 18 | 19 | public static List buildSimpleGrantedAuthorities(final Set roles) { 20 | List authorities = new ArrayList<>(); 21 | for (Role role : roles) { 22 | authorities.add(new SimpleGrantedAuthority(role.getName())); 23 | } 24 | return authorities; 25 | } 26 | 27 | public static SocialProvider toSocialProvider(String providerId) { 28 | for (SocialProvider socialProvider : SocialProvider.values()) { 29 | if (socialProvider.getProviderType().equals(providerId)) { 30 | return socialProvider; 31 | } 32 | } 33 | return SocialProvider.LOCAL; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/validator/PasswordMatches.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import static java.lang.annotation.ElementType.ANNOTATION_TYPE; 4 | import static java.lang.annotation.ElementType.TYPE; 5 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 6 | 7 | import java.lang.annotation.Documented; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.Target; 10 | 11 | import javax.validation.Constraint; 12 | import javax.validation.Payload; 13 | 14 | @Target({ TYPE, ANNOTATION_TYPE }) 15 | @Retention(RUNTIME) 16 | @Constraint(validatedBy = PasswordMatchesValidator.class) 17 | @Documented 18 | public @interface PasswordMatches { 19 | 20 | String message() default "Passwords don't match"; 21 | 22 | Class[] groups() default {}; 23 | 24 | Class[] payload() default {}; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javachinna/validator/PasswordMatchesValidator.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.validator; 2 | 3 | import javax.validation.ConstraintValidator; 4 | import javax.validation.ConstraintValidatorContext; 5 | 6 | import com.javachinna.dto.UserRegistrationForm; 7 | 8 | public class PasswordMatchesValidator implements ConstraintValidator { 9 | 10 | @Override 11 | public boolean isValid(final UserRegistrationForm user, final ConstraintValidatorContext context) { 12 | return user.getPassword().equals(user.getMatchingPassword()); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Database configuration props 2 | spring.datasource.url=jdbc:mysql://localhost:3306/demo?createDatabaseIfNotExist=true 3 | spring.datasource.username=root 4 | spring.datasource.password=chinna44 5 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6 | 7 | # Hibernate props 8 | spring.jpa.show-sql=true 9 | spring.jpa.hibernate.ddl-auto=create 10 | #spring.jpa.hibernate.ddl-auto=validate 11 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 12 | 13 | spring.mvc.view.prefix=/WEB-INF/views/pages/ 14 | spring.mvc.view.suffix=.jsp 15 | 16 | # Social login provider props 17 | spring.security.oauth2.client.registration.google.clientId= 18 | spring.security.oauth2.client.registration.google.clientSecret= 19 | spring.security.oauth2.client.registration.facebook.clientId= 20 | spring.security.oauth2.client.registration.facebook.clientSecret= 21 | spring.security.oauth2.client.provider.facebook.user-info-uri=https://graph.facebook.com/me?fields=id,name,email,picture 22 | spring.security.oauth2.client.registration.github.clientId= 23 | spring.security.oauth2.client.registration.github.clientSecret= 24 | spring.security.oauth2.client.registration.linkedin.clientId= 25 | spring.security.oauth2.client.registration.linkedin.clientSecret= 26 | spring.security.oauth2.client.registration.linkedin.client-authentication-method=post 27 | spring.security.oauth2.client.registration.linkedin.authorization-grant-type=authorization_code 28 | spring.security.oauth2.client.registration.linkedin.scope=r_liteprofile, r_emailaddress 29 | spring.security.oauth2.client.registration.linkedin.redirect-uri-template={baseUrl}/login/oauth2/code/{registrationId} 30 | spring.security.oauth2.client.registration.linkedin.client-name=Linkedin 31 | spring.security.oauth2.client.registration.linkedin.provider=linkedin 32 | spring.security.oauth2.client.provider.linkedin.authorization-uri=https://www.linkedin.com/oauth/v2/authorization 33 | spring.security.oauth2.client.provider.linkedin.token-uri=https://www.linkedin.com/oauth/v2/accessToken 34 | spring.security.oauth2.client.provider.linkedin.user-info-uri=https://api.linkedin.com/v2/me 35 | spring.security.oauth2.client.provider.linkedin.user-name-attribute=id 36 | linkedin.email-address-uri=https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~)) 37 | 38 | # For detailed logging during development 39 | logging.level.com=TRACE 40 | logging.level.org.springframework=TRACE 41 | logging.level.org.hibernate.SQL=TRACE 42 | logging.level.org.hibernate.type=TRACE 43 | -------------------------------------------------------------------------------- /src/main/resources/messages_en.properties: -------------------------------------------------------------------------------- 1 | message.badCredentials=Invalid Credentials 2 | message.regError=An account with this email already exists 3 | message.regSucc=Registered successfully. Please login 4 | NotEmpty=This field is required. 5 | Size.userDto.password=Try one with at least 8 characters. 6 | PasswordMatches.user=Password does not match! 7 | message.logout.success=Logged out successfully 8 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/pages/home.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 2 | <%@ page isELIgnored="false"%> 3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 4 | <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> 5 | 6 | 7 | 8 | home 9 | 10 | 11 |
12 | 13 |

Welcome ${currentUser.displayName} | Logout

14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/pages/login.jsp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/spring-boot-oauth2/a0177ab527c3676658576080e650c69229bef391/src/main/webapp/WEB-INF/views/pages/login.jsp -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/pages/register.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 2 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 3 | <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> 4 | <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 5 | 6 | 7 | 8 | 9 | 10 | Demo 11 | 12 | 13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |

Create Your Account

22 |
23 |
24 |
25 | 26 | 27 |
28 | 29 | 30 |
31 |
32 | 33 | 34 |
35 |
36 | 37 | 38 |
39 |
40 | 41 | 42 | 43 | 44 | ${errors.getGlobalError().defaultMessage} 45 | 46 | 47 |
48 | 49 | 50 |
51 |
52 |

53 | or 54 |

55 |
56 |

57 | Already have an account? 58 | Login Now 59 |

60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | 68 | -------------------------------------------------------------------------------- /src/main/webapp/static/css/style.css: -------------------------------------------------------------------------------- 1 | .content-divider.center { 2 | text-align: center; 3 | } 4 | 5 | .content-divider { 6 | position: relative; 7 | z-index: 1; 8 | } 9 | 10 | .content-divider>span, .content-divider>a { 11 | background-color: #fff; 12 | color: #000; 13 | display: inline-block; 14 | padding: 2px 12px; 15 | border-radius: 3px; 16 | text-transform: uppercase; 17 | font-weight: 500; 18 | } 19 | 20 | .content-divider>span:before, .content-divider>a:before { 21 | content: ""; 22 | position: absolute; 23 | top: 50%; 24 | left: 0; 25 | height: 1px; 26 | background-color: #ddd; 27 | width: 100%; 28 | z-index: -1; 29 | } 30 | 31 | .social-login .btn-img { 32 | width: 30px; 33 | height: auto; 34 | padding: 0.6rem 0; 35 | margin-right: 15px; 36 | } 37 | 38 | .btn-img-linkedin { 39 | width: auto; 40 | height: 50px; 41 | padding: 0.6rem 0; 42 | margin-right: 10px; 43 | } 44 | 45 | .form-group .has-error { 46 | color: red; 47 | } -------------------------------------------------------------------------------- /src/main/webapp/static/img/facebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/spring-boot-oauth2/a0177ab527c3676658576080e650c69229bef391/src/main/webapp/static/img/facebook.png -------------------------------------------------------------------------------- /src/main/webapp/static/img/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/spring-boot-oauth2/a0177ab527c3676658576080e650c69229bef391/src/main/webapp/static/img/github.png -------------------------------------------------------------------------------- /src/main/webapp/static/img/google.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/spring-boot-oauth2/a0177ab527c3676658576080e650c69229bef391/src/main/webapp/static/img/google.png -------------------------------------------------------------------------------- /src/main/webapp/static/img/linkedin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChinna/spring-boot-oauth2/a0177ab527c3676658576080e650c69229bef391/src/main/webapp/static/img/linkedin.png -------------------------------------------------------------------------------- /src/test/java/com/javachinna/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.javachinna.demo; 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 DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------