├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── stewlutions │ │ │ └── azuread_springsecurity5_oidc │ │ │ └── kickstart │ │ │ ├── KickstartApplication.java │ │ │ ├── SecurityConfig.java │ │ │ ├── StubController.java │ │ │ └── replacements │ │ │ ├── KickstartOAuth2UserService.java │ │ │ └── KickstartUserInfoResponseClient.java │ └── resources │ │ └── application.yaml └── test │ └── java │ └── com │ └── stewlutions │ └── azuread_springsecurity5_oidc │ └── kickstart │ └── KickstartApplicationTests.java └── target └── classes └── application.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Stewart Adam 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 | AzureAD, Spring Security 5, and OAuth 2 Login Kickstart 2 | ====== 3 | A minimal Spring Boot 2.0 project demonstrating how to integrate Azure AD with the new Spring Security 5 + OAuth 2 login features. 4 | 5 | ## Why? 6 | Because Spring Security recently moved some of the functionality from the previously recommended `spring-security-oauth` package into core, and will replace it entirely over time. See [this compatibility matrix](https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Features-Matrix) for details. Many examples on the web are no longer compatible with Spring Boot 2.0 / Spring Security 5.0 after this breaking change. 7 | 8 | ## How does it work? 9 | 1. Edit `src/main/resources/application.yaml` and plug in your Azure AD application's client ID and secret. The app needs to be registered in Azure AD with at least the "Sign-in and read user profile" permission (i.e. User.Read scope) against *Microsoft Graph* (not the default Windows Azure AD Graph API that is added for new apps). 10 | 2. Run `mvn spring-boot:run` to start the local webserver. 11 | 3. Open one of the endpoints below in your browser of choice 12 | 13 | ## Available Endpoints 14 | 1. `http://localhost:8080/hello/foo`: echoes `foo` back at you (for your choice of `foo`) 15 | 2. `http://localhost:8080/oauth2/authorization/microsoft`: attempts to login the user using the OAuth2 code grant against AAD, followed by a Graph call to obtain user information 16 | 3. `http://localhost:8080/claims`: Displays info on the currently logged in user 17 | 18 | Note that because no homepage is configured, after login you'll get a 404 error when hitting `http://localhost:8080`. This is expected; hit the `/claims` endpoint to verify that your session has the claims stored. 19 | 20 | ## References: 21 | I found these resources helpful while troubleshooting: 22 | 23 | - [Spring Security's OAuth2 feature matrix](https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Features-Matrix) 24 | - [Spring Security 5 OAuth 2.0 Login Sample (Okta)](https://github.com/spring-projects/spring-security/tree/master/samples/boot/oauth2login#okta-login) 25 | - [Spring Security 5 -- OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) by Loredana Crusoveanu 26 | - [Overriding Spring Boot 2.0 Auto-configuration](https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/reference/htmlsingle#jc-oauth2login-completely-override-autoconfiguration) from Spring docs 27 | - (Deprecated) [Spring Boot and OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2/) tutorial 28 | - [Spring Boot's OAuth2 Client](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html#boot-features-security-oauth2-client) from Spring docs 29 | - ['cannot be null' errors in Spring Security 5](https://stackoverflow.com/questions/49315552/authorizationgranttype-cannot-be-null-in-spring-security-5-oauth-client-and-spri) 30 | 31 | A lesson learned: searching specifically for Spring Security 5's OAuth2 implementation is near impossible since you always end up getting results for the older "Spring Security OAuth" 2.x implementation, even if you put a time restriction on results such as "within last year". 32 | 33 | Based on lots of trial and error, I would caution that you are **not** reading about the new Spring Security 5's OAuth2 implementation if you see: 34 | 1. `@EnableOAuth2Sso` in the code sample 35 | 2. The properties/YAML configuration start directly with `security` (instead of `spring` followed by `security`, which indicates for Spring Security 5) 36 | 3. The properties/YAML configuration in [camelCase](https://github.com/spring-guides/tut-spring-boot-oauth2/blob/master/auth-server/src/main/resources/application.yml) (new config in Spring Security 5 is [snake-case](https://github.com/spring-projects/spring-security/blob/master/samples/boot/oauth2login/src/main/resources/application.yml)) 37 | 4. A dependency on the `spring-security-oauth2` package in `pom.xml` (but `spring-security-oauth2-client` or `spring-security-oauth2-jose` would be OK for Spring Security 5) 38 | 39 | *Disclaimer: I am not a Spring framework expert, this is my best guess from limited experience with it* 40 | 41 | ## Known issues 42 | Java 8 (and possibly later) [default to an invalid Accept header value](https://bugs.openjdk.java.net/browse/JDK-8163921) of `text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2` which upsets many API endpoints, including Microsoft Graph (besides the point that a REST endpoint is not going to be able to spit back user info in HTML/GIF/JPEG format to Java). 43 | 44 | As a result, two classes from Spring needed to be customized (e.g. copied and lightly modified) in order to ensure the appropriate Accept header was used. You will find these two classes in the `replacements` sub-package. 45 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.stewlutions.azuread_springsecurity5 7 | kickstart 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | kickstart 12 | Sample showing Azure AD integration with Spring Boot 2.0 (Spring Security 5) 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-security 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.security 38 | spring-security-oauth2-client 39 | 5.0.3.RELEASE 40 | 41 | 42 | org.springframework.security 43 | spring-security-oauth2-jose 44 | 5.0.3.RELEASE 45 | 46 | 47 | com.microsoft.azure 48 | adal4j 49 | 1.4.0 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | org.springframework.security 59 | spring-security-test 60 | test 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-maven-plugin 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /src/main/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/KickstartApplication.java: -------------------------------------------------------------------------------- 1 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class KickstartApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(KickstartApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart; 2 | 3 | import com.stewlutions.azuread_springsecurity5_oidc.kickstart.replacements.KickstartOAuth2UserService; 4 | 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | import org.springframework.security.oauth2.core.user.OAuth2User; 9 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; 10 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 11 | 12 | @EnableWebSecurity 13 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 14 | 15 | @Override 16 | protected void configure(HttpSecurity http) throws Exception { 17 | http 18 | .authorizeRequests() 19 | .anyRequest().permitAll() 20 | .and() 21 | .oauth2Login() 22 | .userInfoEndpoint().userService(this.oauth2UserService()) 23 | ; 24 | } 25 | 26 | private OAuth2UserService oauth2UserService() { 27 | return new KickstartOAuth2UserService(); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/StubController.java: -------------------------------------------------------------------------------- 1 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart; 2 | 3 | import java.text.MessageFormat; 4 | 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | import org.springframework.web.servlet.ModelAndView; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | import com.microsoft.aad.adal4j.AuthenticationContext; 12 | 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.ui.ModelMap; 15 | import org.springframework.web.bind.annotation.PathVariable; 16 | 17 | @RestController 18 | class StubController { 19 | 20 | @RequestMapping("/hello/{name}") 21 | String hello(@PathVariable String name) { 22 | return "Hello, " + name + "!"; 23 | } 24 | 25 | @RequestMapping("/claims") 26 | String claims() { 27 | return "Data: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); 28 | } 29 | 30 | @RequestMapping("/patient/{id}") 31 | ModelAndView patient(ModelMap model, HttpServletRequest request, @PathVariable String id) { 32 | model.addAttribute("attribute", "forwardWithForwardPrefix"); 33 | 34 | String client_id = ""; 35 | int state = (int )(Math.random() * 1000000 + 1); 36 | String resource = "client_id_guid_of_fhir"; 37 | String base_uri = request.getRequestURL().toString(); 38 | base_uri = base_uri.substring(0, base_uri.length() - request.getServletPath().length()); 39 | String redirect_uri = base_uri + "/context/authorized"; 40 | 41 | String redirect = String.format("https://login.microsoftonline.com/common/oauth2/authorize?client_id=%s&state=%s&resource=%s&redirect_uri=%s&response_type=code&response_mode=post", client_id, state, resource, redirect_uri); 42 | return new ModelAndView("redirect:" + redirect, model); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/replacements/KickstartOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart.replacements; 17 | 18 | import org.springframework.core.ParameterizedTypeReference; 19 | import org.springframework.security.core.GrantedAuthority; 20 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 21 | import org.springframework.security.oauth2.core.OAuth2Error; 22 | import org.springframework.security.oauth2.core.user.DefaultOAuth2User; 23 | import org.springframework.security.oauth2.core.user.OAuth2User; 24 | import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; 25 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 26 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; 27 | import org.springframework.util.Assert; 28 | import org.springframework.util.StringUtils; 29 | 30 | import java.util.HashSet; 31 | import java.util.Map; 32 | import java.util.Set; 33 | 34 | /** 35 | * An implementation of an {@link OAuth2UserService} that supports standard OAuth 2.0 Provider's. 36 | *

37 | * For standard OAuth 2.0 Provider's, the attribute name used to access the user's name 38 | * from the UserInfo response is required and therefore must be available via 39 | * {@link org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint#getUserNameAttributeName() UserInfoEndpoint.getUserNameAttributeName()}. 40 | *

41 | * NOTE: Attribute names are not standardized between providers and therefore will vary. 42 | * Please consult the provider's API documentation for the set of supported user attribute names. 43 | * 44 | * @author Joe Grandja 45 | * @since 5.0 46 | * @see OAuth2UserService 47 | * @see OAuth2UserRequest 48 | * @see OAuth2User 49 | * @see DefaultOAuth2User 50 | */ 51 | public class KickstartOAuth2UserService implements OAuth2UserService { 52 | private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri"; 53 | private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute"; 54 | private KickstartUserInfoResponseClient userInfoResponseClient = new KickstartUserInfoResponseClient(); 55 | 56 | @Override 57 | public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { 58 | Assert.notNull(userRequest, "userRequest cannot be null"); 59 | 60 | if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) { 61 | OAuth2Error oauth2Error = new OAuth2Error( 62 | MISSING_USER_INFO_URI_ERROR_CODE, 63 | "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + 64 | userRequest.getClientRegistration().getRegistrationId(), 65 | null 66 | ); 67 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); 68 | } 69 | String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(); 70 | if (!StringUtils.hasText(userNameAttributeName)) { 71 | OAuth2Error oauth2Error = new OAuth2Error( 72 | MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, 73 | "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + 74 | userRequest.getClientRegistration().getRegistrationId(), 75 | null 76 | ); 77 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); 78 | } 79 | 80 | ParameterizedTypeReference> typeReference = 81 | new ParameterizedTypeReference>() {}; 82 | Map userAttributes = this.userInfoResponseClient.getUserInfoResponse(userRequest, typeReference); 83 | GrantedAuthority authority = new OAuth2UserAuthority(userAttributes); 84 | Set authorities = new HashSet<>(); 85 | authorities.add(authority); 86 | 87 | return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName); 88 | } 89 | } -------------------------------------------------------------------------------- /src/main/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/replacements/KickstartUserInfoResponseClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart.replacements; 17 | 18 | import com.nimbusds.oauth2.sdk.ErrorObject; 19 | import com.nimbusds.oauth2.sdk.ParseException; 20 | import com.nimbusds.oauth2.sdk.http.HTTPRequest; 21 | import com.nimbusds.oauth2.sdk.http.HTTPResponse; 22 | import com.nimbusds.oauth2.sdk.token.BearerAccessToken; 23 | import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse; 24 | import com.nimbusds.openid.connect.sdk.UserInfoRequest; 25 | import org.springframework.core.ParameterizedTypeReference; 26 | import org.springframework.http.HttpHeaders; 27 | import org.springframework.http.client.AbstractClientHttpResponse; 28 | import org.springframework.http.client.ClientHttpResponse; 29 | import org.springframework.http.converter.GenericHttpMessageConverter; 30 | import org.springframework.http.converter.HttpMessageNotReadableException; 31 | import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 32 | import org.springframework.security.authentication.AuthenticationServiceException; 33 | import org.springframework.security.oauth2.client.registration.ClientRegistration; 34 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 35 | import org.springframework.security.oauth2.core.OAuth2AccessToken; 36 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 37 | import org.springframework.security.oauth2.core.OAuth2Error; 38 | import org.springframework.util.Assert; 39 | 40 | import java.io.ByteArrayInputStream; 41 | import java.io.IOException; 42 | import java.io.InputStream; 43 | import java.net.URI; 44 | import java.nio.charset.Charset; 45 | 46 | /** 47 | * NOTE: This is a copy of org.springframework.security.oauth2.client.userinfo.NimbusUserInfoResponseClient 48 | * 49 | * @author Joe Grandja (modifications by Stewart Adam to fix Accept header) 50 | * @since 5.0 51 | */ 52 | final class KickstartUserInfoResponseClient { 53 | private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response"; 54 | private final GenericHttpMessageConverter genericHttpMessageConverter = new MappingJackson2HttpMessageConverter(); 55 | 56 | T getUserInfoResponse(OAuth2UserRequest userInfoRequest, Class returnType) throws OAuth2AuthenticationException { 57 | ClientHttpResponse userInfoResponse = this.getUserInfoResponse( 58 | userInfoRequest.getClientRegistration(), userInfoRequest.getAccessToken()); 59 | try { 60 | return (T) this.genericHttpMessageConverter.read(returnType, userInfoResponse); 61 | } catch (IOException | HttpMessageNotReadableException ex) { 62 | OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, 63 | "An error occurred reading the UserInfo Success response: " + ex.getMessage(), null); 64 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); 65 | } 66 | } 67 | 68 | T getUserInfoResponse(OAuth2UserRequest userInfoRequest, ParameterizedTypeReference typeReference) throws OAuth2AuthenticationException { 69 | ClientHttpResponse userInfoResponse = this.getUserInfoResponse( 70 | userInfoRequest.getClientRegistration(), userInfoRequest.getAccessToken()); 71 | try { 72 | return (T) this.genericHttpMessageConverter.read(typeReference.getType(), null, userInfoResponse); 73 | } catch (IOException | HttpMessageNotReadableException ex) { 74 | OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, 75 | "An error occurred reading the UserInfo Success response: " + ex.getMessage(), null); 76 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); 77 | } 78 | } 79 | 80 | private ClientHttpResponse getUserInfoResponse(ClientRegistration clientRegistration, 81 | OAuth2AccessToken oauth2AccessToken) throws OAuth2AuthenticationException { 82 | URI userInfoUri = URI.create(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()); 83 | BearerAccessToken accessToken = new BearerAccessToken(oauth2AccessToken.getTokenValue()); 84 | 85 | UserInfoRequest userInfoRequest = new UserInfoRequest(userInfoUri, accessToken); 86 | HTTPRequest httpRequest = userInfoRequest.toHTTPRequest(); 87 | httpRequest.setHeader("Accept", "application/json"); 88 | httpRequest.setConnectTimeout(30000); 89 | httpRequest.setReadTimeout(30000); 90 | HTTPResponse httpResponse; 91 | 92 | try { 93 | httpResponse = httpRequest.send(); 94 | } catch (IOException ex) { 95 | throw new AuthenticationServiceException("An error occurred while sending the UserInfo Request: " + 96 | ex.getMessage(), ex); 97 | } 98 | 99 | if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) { 100 | return new NimbusClientHttpResponse(httpResponse); 101 | } 102 | 103 | UserInfoErrorResponse userInfoErrorResponse; 104 | try { 105 | userInfoErrorResponse = UserInfoErrorResponse.parse(httpResponse); 106 | } catch (ParseException ex) { 107 | OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, 108 | "An error occurred parsing the UserInfo Error response: " + ex.getMessage(), null); 109 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); 110 | } 111 | ErrorObject errorObject = userInfoErrorResponse.getErrorObject(); 112 | 113 | StringBuilder errorDescription = new StringBuilder(); 114 | errorDescription.append("An error occurred while attempting to access the UserInfo Endpoint -> "); 115 | errorDescription.append("Error details: ["); 116 | errorDescription.append("UserInfo Uri: ").append(userInfoUri.toString()); 117 | errorDescription.append(", Http Status: ").append(errorObject.getHTTPStatusCode()); 118 | if (errorObject.getCode() != null) { 119 | errorDescription.append(", Error Code: ").append(errorObject.getCode()); 120 | } 121 | if (errorObject.getDescription() != null) { 122 | errorDescription.append(", Error Description: ").append(errorObject.getDescription()); 123 | } 124 | errorDescription.append("]"); 125 | 126 | OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorDescription.toString(), null); 127 | throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); 128 | } 129 | 130 | private static class NimbusClientHttpResponse extends AbstractClientHttpResponse { 131 | private final HTTPResponse httpResponse; 132 | private final HttpHeaders headers; 133 | 134 | private NimbusClientHttpResponse(HTTPResponse httpResponse) { 135 | Assert.notNull(httpResponse, "httpResponse cannot be null"); 136 | this.httpResponse = httpResponse; 137 | this.headers = new HttpHeaders(); 138 | this.headers.setAll(httpResponse.getHeaders()); 139 | } 140 | 141 | @Override 142 | public int getRawStatusCode() throws IOException { 143 | return this.httpResponse.getStatusCode(); 144 | } 145 | 146 | @Override 147 | public String getStatusText() throws IOException { 148 | return String.valueOf(this.getRawStatusCode()); 149 | } 150 | 151 | @Override 152 | public void close() { 153 | } 154 | 155 | @Override 156 | public InputStream getBody() throws IOException { 157 | InputStream inputStream = new ByteArrayInputStream( 158 | this.httpResponse.getContent().getBytes(Charset.forName("UTF-8"))); 159 | return inputStream; 160 | } 161 | 162 | @Override 163 | public HttpHeaders getHeaders() { 164 | return this.headers; 165 | } 166 | } 167 | } -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | security: 3 | oauth2: 4 | client: 5 | registration: 6 | microsoft: 7 | client-id: aad-app-clientId-guid 8 | client-secret: aad-app-clientSecret-key 9 | authorization-grant-type: authorization_code 10 | redirect-uri-template: '{baseUrl}/login/oauth2/code/{registrationId}' 11 | scope: User.Read 12 | client-name: Microsoft 13 | client-alias: microsoft 14 | provider: 15 | microsoft: 16 | authorization-uri: https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/ 17 | token-uri: https://login.microsoftonline.com/common/oauth2/token 18 | user-info-uri: https://graph.microsoft.com/v1.0/me 19 | user-name-attribute: id 20 | jwk-set-uri: https://login.microsoftonline.com/common/discovery/keys -------------------------------------------------------------------------------- /src/test/java/com/stewlutions/azuread_springsecurity5_oidc/kickstart/KickstartApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.stewlutions.azuread_springsecurity5_oidc.kickstart; 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 KickstartApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /target/classes/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | security: 3 | oauth2: 4 | client: 5 | registration: 6 | microsoft: 7 | client-id: d2a196a1-2148-4500-9497-ca51107037da 8 | client-secret: 0tuLaOxwj0e5xGGdxp6418gSG9riHDL5FD5IqnzHs4w= 9 | authorization-grant-type: authorization_code 10 | redirect-uri-template: '{baseUrl}/login/oauth2/code/{registrationId}' 11 | scope: User.Read 12 | client-name: Microsoft 13 | client-alias: microsoft 14 | provider: 15 | microsoft: 16 | authorization-uri: https://login.microsoftonline.com/common/oauth2/authorize?resource=https://graph.microsoft.com/ 17 | token-uri: https://login.microsoftonline.com/common/oauth2/token 18 | user-info-uri: https://graph.microsoft.com/v1.0/me 19 | user-name-attribute: id 20 | jwk-set-uri: https://login.microsoftonline.com/common/discovery/keys --------------------------------------------------------------------------------