├── src ├── main │ ├── resources │ │ └── application.properties │ └── kotlin │ │ └── com │ │ └── traeper │ │ └── oauth2 │ │ └── authorization │ │ ├── Application.kt │ │ ├── application │ │ └── user │ │ │ └── UserController.kt │ │ └── configuration │ │ └── SecurityConfiguration.kt └── test │ └── kotlin │ └── com │ └── traeper │ └── oauth2 │ └── authorization │ └── ApplicationTests.kt ├── settings.gradle.kts ├── resources ├── oauth2.png ├── oauth2-protocol-flow.png ├── FilterChainProxy-oauth2.png ├── client-credentials-grant.png └── spring-authorization-server-reference.png ├── gradle └── wrapper │ └── gradle-wrapper.properties ├── .gitignore ├── HELP.md ├── gradlew.bat ├── gradlew └── README.md /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "oauth2.authorization" 2 | -------------------------------------------------------------------------------- /resources/oauth2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/traeper/spring-authorization-server-practice/HEAD/resources/oauth2.png -------------------------------------------------------------------------------- /resources/oauth2-protocol-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/traeper/spring-authorization-server-practice/HEAD/resources/oauth2-protocol-flow.png -------------------------------------------------------------------------------- /resources/FilterChainProxy-oauth2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/traeper/spring-authorization-server-practice/HEAD/resources/FilterChainProxy-oauth2.png -------------------------------------------------------------------------------- /resources/client-credentials-grant.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/traeper/spring-authorization-server-practice/HEAD/resources/client-credentials-grant.png -------------------------------------------------------------------------------- /resources/spring-authorization-server-reference.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/traeper/spring-authorization-server-practice/HEAD/resources/spring-authorization-server-reference.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .gradle 3 | build 4 | .DS_Store 5 | 6 | # Compiled class file 7 | *.class 8 | 9 | # Log file 10 | *.log 11 | 12 | # Package Files # 13 | *.jar 14 | *.war 15 | *.nar 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* -------------------------------------------------------------------------------- /src/main/kotlin/com/traeper/oauth2/authorization/Application.kt: -------------------------------------------------------------------------------- 1 | package com.traeper.oauth2.authorization 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class Application 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /src/test/kotlin/com/traeper/oauth2/authorization/ApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.traeper.oauth2.authorization 2 | 3 | import com.nimbusds.jose.util.Base64 4 | import org.junit.jupiter.api.Test 5 | 6 | class ApplicationTests { 7 | 8 | @Test 9 | fun generateAuthorizationBasicHeader() { 10 | val clientId = "aaaa" 11 | val clientSecret = "bbbb" 12 | val encoded = Base64.encode("$clientId:$clientSecret") 13 | println(encoded) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/kotlin/com/traeper/oauth2/authorization/application/user/UserController.kt: -------------------------------------------------------------------------------- 1 | package com.traeper.oauth2.authorization.application.user 2 | 3 | import org.springframework.web.bind.annotation.GetMapping 4 | import org.springframework.web.bind.annotation.RequestMapping 5 | import org.springframework.web.bind.annotation.RestController 6 | 7 | @RequestMapping("/v1/users") 8 | @RestController 9 | class UserController { 10 | 11 | @GetMapping("/me") 12 | fun getMyInfo(): UserInfoResponse = 13 | UserInfoResponse("traeper") 14 | 15 | data class UserInfoResponse( 16 | val nickname: String, 17 | ) 18 | } 19 | -------------------------------------------------------------------------------- /HELP.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ### Reference Documentation 4 | For further reference, please consider the following sections: 5 | 6 | * [Official Gradle documentation](https://docs.gradle.org) 7 | * [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.4/gradle-plugin/reference/html/) 8 | * [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.4/gradle-plugin/reference/html/#build-image) 9 | * [Spring Security](https://docs.spring.io/spring-boot/docs/3.0.4/reference/htmlsingle/#web.security) 10 | * [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.4/reference/htmlsingle/#web) 11 | 12 | ### Guides 13 | The following guides illustrate how to use some features concretely: 14 | 15 | * [Securing a Web Application](https://spring.io/guides/gs/securing-web/) 16 | * [Spring Boot and OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2/) 17 | * [Authenticating a User with LDAP](https://spring.io/guides/gs/authenticating-ldap/) 18 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 19 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 20 | * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) 21 | 22 | ### Additional Links 23 | These additional references should also help you: 24 | 25 | * [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) 26 | 27 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /src/main/kotlin/com/traeper/oauth2/authorization/configuration/SecurityConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.traeper.oauth2.authorization.configuration 2 | 3 | import com.nimbusds.jose.jwk.JWKSet 4 | import com.nimbusds.jose.jwk.RSAKey 5 | import com.nimbusds.jose.jwk.source.ImmutableJWKSet 6 | import com.nimbusds.jose.jwk.source.JWKSource 7 | import com.nimbusds.jose.proc.SecurityContext 8 | import org.springframework.context.annotation.Bean 9 | import org.springframework.context.annotation.Configuration 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 11 | import org.springframework.security.oauth2.core.AuthorizationGrantType 12 | import org.springframework.security.oauth2.core.ClientAuthenticationMethod 13 | import org.springframework.security.oauth2.jwt.JwtDecoder 14 | import org.springframework.security.oauth2.jwt.JwtEncoder 15 | import org.springframework.security.oauth2.jwt.NimbusJwtEncoder 16 | import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService 17 | import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService 18 | import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository 19 | import org.springframework.security.oauth2.server.authorization.client.RegisteredClient 20 | import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository 21 | import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration 22 | import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer 23 | import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings 24 | import org.springframework.security.oauth2.server.authorization.settings.ClientSettings 25 | import org.springframework.security.oauth2.server.authorization.settings.TokenSettings 26 | import org.springframework.security.oauth2.server.authorization.token.JwtGenerator 27 | import org.springframework.security.web.SecurityFilterChain 28 | import java.security.KeyPair 29 | import java.security.KeyPairGenerator 30 | import java.security.interfaces.RSAPrivateKey 31 | import java.security.interfaces.RSAPublicKey 32 | import java.time.Duration 33 | import java.util.UUID 34 | 35 | @Configuration 36 | class SecurityConfiguration { 37 | 38 | @Bean 39 | fun filterChain( 40 | http: HttpSecurity, 41 | registeredClientRepository: RegisteredClientRepository, 42 | authorizationService: OAuth2AuthorizationService, 43 | jwtEncoder: JwtEncoder, 44 | settings: AuthorizationServerSettings, 45 | ): SecurityFilterChain { 46 | OAuth2AuthorizationServerConfigurer() 47 | .apply { http.apply(this) } 48 | .registeredClientRepository(registeredClientRepository) 49 | .authorizationService(authorizationService) 50 | .tokenGenerator(JwtGenerator(jwtEncoder)) 51 | .authorizationServerSettings(settings) 52 | 53 | // ResourceServer의 역할도 겸하기 위한 Security 기본 설정 54 | http.csrf().disable() 55 | http.securityContext() 56 | http.authorizeHttpRequests() 57 | .anyRequest().authenticated() 58 | 59 | // jwt 60 | http.oauth2ResourceServer() 61 | .jwt() 62 | 63 | return http.build() 64 | } 65 | 66 | @Bean 67 | fun registeredClientRepository(): RegisteredClientRepository { 68 | val registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()) 69 | .clientName("jay client") 70 | .clientId("aaaa") 71 | .clientSecret("{noop}bbbb") 72 | .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) // Authorization: Basic {base64 encoded String} 73 | .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) // client_credentials 이용 74 | .clientSettings(ClientSettings.builder().build()) 75 | .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofHours(2)).build()) // 토큰 2시간 유효 76 | .build() 77 | return InMemoryRegisteredClientRepository(registeredClient) 78 | } 79 | 80 | @Bean 81 | fun authorizationService(): OAuth2AuthorizationService = 82 | InMemoryOAuth2AuthorizationService() 83 | 84 | /** 85 | * jwt 생성에 필요한 RSA키 generate, 실제 운영에 사용하려면 KeyStore에 저장해야한다. 86 | */ 87 | @Bean 88 | fun jwkSource(): JWKSource { 89 | val keyPair: KeyPair = generateRsaKey() 90 | val publicKey: RSAPublicKey = keyPair.public as RSAPublicKey 91 | val privateKey: RSAPrivateKey = keyPair.private as RSAPrivateKey 92 | val rsaKey: RSAKey = RSAKey.Builder(publicKey) 93 | .privateKey(privateKey) 94 | .keyID(UUID.randomUUID().toString()) 95 | .build() 96 | val jwkSet = JWKSet(rsaKey) 97 | return ImmutableJWKSet(jwkSet) 98 | } 99 | 100 | private fun generateRsaKey(): KeyPair = 101 | try { 102 | val keyPairGenerator = KeyPairGenerator.getInstance("RSA") 103 | keyPairGenerator.initialize(2048) 104 | keyPairGenerator.generateKeyPair() 105 | } catch (ex: Exception) { 106 | throw IllegalStateException(ex) 107 | } 108 | 109 | @Bean 110 | fun jwtDecoder(jwkSource: JWKSource): JwtDecoder = 111 | OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource) 112 | 113 | @Bean 114 | fun jwtEncoder(jwkSource: JWKSource): JwtEncoder = 115 | NimbusJwtEncoder(jwkSource) 116 | 117 | /** 118 | * 여러 endpoint URI를 커스터마이징할 수 있다. 119 | */ 120 | @Bean 121 | fun authorizationServerSettings(): AuthorizationServerSettings = 122 | AuthorizationServerSettings.builder().tokenEndpoint("/custom-uri/oauth2/token").build() 123 | } 124 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Authorization Server Practice 2 | Spring Authorization Server 프레임워크는 OAuth 2.0 중 Authorization Server 부분을 쉽게 구현할 수 있게 해준다. 3 | 우선 OAuth 2.0에 대해 간략히 살펴보자. 4 | 5 | ## OAuth 2.0 6 | ![](./resources/oauth2.png) 7 | 8 | rfc6749 문서에 따르면 'OAuth 2.0 인가(인증) 프레임워크'라는 말로 OAuth 2.0을 풀이한다. 9 | OAuth 2.0은 서드파티 앱이 특정 서비스의 제한이 걸린 자원에 접근하기 위해 리소스 오너(사용자)의 허락을 받아 자원에 접근을 하게되는 일련의 플로우를 제공한다. 10 | 구글, 페이스북 등 유수의 IT 기업들은 자신의 우수한 회원 체계, 여러 코어 서비스를 바탕으로 OAuth 2.0 서비스를 제공하고 있다. 11 | 12 | rfc문서에서는 프레임워크라고 말하는데 알고리즘, 프로토콜 같은 조그만 범위를 넘어 일종의 체계화된 틀이며 이 틀에 맞춰 충실히 스펙을 구현하면 된다는 말로도 이해할 수 있다. 이어서 말하겠지만 OAuth 2.0의 구조는 단순한 편이 결코 아니다. 13 | 14 | ### Protocol Flow 15 | 16 | ![](./resources/oauth2-protocol-flow.png) 17 | 18 | OAuth 2.0의 구성요소를 살펴보자. 19 | * Client : Protected Resource에 접근하고 싶어하는 주체이며 웹앱, 모바일앱, 기타 프로그램 중 어떤 것도 될 수 있다. 20 | * Resource Owner : Protected Resource에 대한 접근을 허용하는 주체이며 대부분의 경우 end-user, 즉 사용자를 의미한다. 21 | * Authorization Server : Resource Owner를 인증하고 Access Token을 발급하는 서버. 22 | * Resource Server : Access Token을 파라미터로 받아 검증하고 Protected Resource을 제공하는 서버. 23 | 24 | Protocol Flow를 간단히 살펴보면 아래와 같다. 25 | * (A), (B), (C), (D) : 인증을 통한 Access Token 획득 26 | * (E), (F) : Access Token을 이용한 Protected Resource을 이용 27 | 28 | ### Client Credentials Grant 29 | OAuth 2.0 여러 인증 방식 중 Server to Server 구현에 해당하며 가장 간단한 **Client Credentials Grant**을 구현해보고자 한다. 30 | 31 | ![](./resources/client-credentials-grant.png) 32 | 33 | 이 방식은 Client와 Authorization Server 간 보안 환경(SSL) 등 신뢰할 수 있는 구간에서 활용할 수 있는 방식이다. Client는 Access Token을 얻은 다음 Resource Server에 접근하여 Protected Resource에 접근할 수 있다. 34 | 35 | 이 Protocol Flow가 동작하기 전에 Authorization Server에서 ClientId, ClientSecret을 생성한 다음 Client가 이를 갖고 있는 상황에서 진행해야 한다. 36 | 37 | ## Authorization Server Practice 38 | OAuth 2.0에 대해 여러 구현이 있지만 23년 3월 기준으로 최신 구현인 Spring Authorization Server 프레임워크를 이용하고자 한다. 39 | 이 프레임워크도 Spring Security의 SecurityFilterChain 기반으로 동작하므로 Spring Security에 대한 이해가 선행되어 있어야 한다. 40 | 41 | ![](./resources/spring-authorization-server-reference.png) 42 | 위 이미지는 공식 Reference 문서이다. Access Token을 발급하는 부분을 보고 싶으면 Protocol Endpoints -> OAuth2 Token Endpoint를 참조하면 된다. 43 | 해당 가이드에서는 AccessTokenRequestConverter, AuthenticationProvider, AccessTokenResponseHandler 등 SecurityFilterChain 구현체에 참여하는 다양한 요소들에 대해 커스터마이저를 제공하지만 커스터마이징을 할 필요는 거의 없을 것이다. 프레임워크가 rfc 문서에 적혀있는 OAuth 2.0 프레임워크의 스펙을 대부분 커버하므로 그대로 활용하면 될 뿐이다. 44 | 45 | ClientId, ClientSecret 등 Client Authentication 동작에 필요한 저장소는 RegisteredClientRepository을 구현하면 되는데, In-Memory, Jdbc 구현체를 기본적으로 제공하며 [JPA 기반으로 작성된 예제](https://docs.spring.io/spring-authorization-server/docs/current/reference/html/guides/how-to-jpa.html)도 충분히 제공하고 있다. JPA로 구현을 해봤었는데 이번에는 간단하게 In-Memory로 구현해보겠다. 46 | 47 | ### Security Configuration 48 | [SecurityConfiguration](./src/main/kotlin/com/traeper/oauth2/authorization/configuration/SecurityConfiguration.kt) 파일을 보면 심플하게 구현된 SecurityFilterChain을 볼 수 있다. Reference가 워낙 잘 나와서 보고 따라 적으면 되는 수준이긴 하다. 👍 49 | Client Credentials Grant 방식에 Authorization Basic Header를 이용한 인증 방식을 지원하기 위해 RegisteredClientRepository의 구현체는 아래처럼 커스터마이징 했다. 참고로 Access Token, Refresh Token 등의 유효시간도 설정할 수 있다. 50 | ```kotlin 51 | @Bean 52 | fun registeredClientRepository(): RegisteredClientRepository { 53 | val registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()) 54 | // .. 55 | .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) // Authorization: Basic {base64 encoded String} 56 | .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) // client_credentials 이용 57 | .tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofHours(2)).build()) // 토큰 2시간 유효 58 | .build() 59 | return InMemoryRegisteredClientRepository(registeredClient) 60 | } 61 | ``` 62 | 63 | 간편한 테스트를 위해 Resource Server의 역할도 겸하게 하였으며 구현이 간편한 jwt를 이용하도록 설정을 잡았다. 64 | 만약 Opaque Token을 이용하려 한다면 프레임워크 기본 구현체가 Resource Server에서 RestTemplate로 Authorization Server을 호출해야하므로 두 서버를 따로 뛰워야 하는 불편함이 있다. 65 | 66 | ### 간단한 API 코드 작성 67 | Security 설정이 잘 되었는지 확인하기 위해 샘플 API를 작성했다. 68 | 69 | ```kotlin 70 | @RequestMapping("/v1/users") 71 | @RestController 72 | class UserController { 73 | 74 | @GetMapping("/me") 75 | fun getMyInfo(): UserInfoResponse = 76 | UserInfoResponse("traeper") 77 | 78 | data class UserInfoResponse( 79 | val nickname: String, 80 | ) 81 | } 82 | ``` 83 | 84 | ### 테스트하기 85 | 서버를 띄우고 이것저것 테스트를 해보자. (불필요한 헤더는 생략) 86 | 87 | 1. 인증 없이 API 호출 88 | ```shell 89 | curl -X GET http://localhost:8080/v1/users/me -v 90 | < HTTP/1.1 401 91 | < WWW-Authenticate: Bearer 92 | ``` 93 | 인증 없이 API를 호출하면 401 응답을 받게 되며 `WWW-Authenticate: Bearer`를 받게 된다. client가 유효하지 않을 때 내려주는 헤더값인데 Bearer로 인증하라는 것을 알 수 있다. 94 | 95 | 2. Access Token 발급 시도 (client_secret_basic 헤더 없이) 96 | ```shell 97 | curl -X POST http://localhost:8080/custom-uri/oauth2/token\?grant_type\=client_credentials \ 98 | --header 'Content-Type: application/x-www-form-urlencoded' -v 99 | < HTTP/1.1 401 100 | ``` 101 | client_secret_basic 헤더가 없어서 401이 발생하지만 WWW-Authenticate는 보이지 않는다. Basic 헤더를 잘 넘겨주자..! 102 | 103 | 3. Access Token 발급 시도 (client_secret_basic 헤더와 함께) 104 | 105 | client_secret_basic 헤더의 포맷은 `Authorization: Basic {base64 encoded string}`이다. 106 | `{clientId}:{clientSecret}`의 복합 문장을 base64 인코딩하면 끝이다. 예시는 [테스트케이스](./src/test/kotlin/com/traeper/oauth2/authorization/ApplicationTests.kt)로 구현해뒀다. 107 | 108 | clientSecret을 잘못 입력한 경우 401헤더와 함께 `{"error":"invalid_client"}` 같은 응답이 내려오기도 한다. clientSecret은 spring security에서 제공하는 DelegatingPasswordEncoder을 이용하므로 테스트 시 참고하자. 본 예제에서는 {noop}으로 했으니 평문 비교를 한다. 현업에서 활용할 때는 해싱을 지원하는 bcrypt 알고리즘 등으로 clientSecret을 인코딩해서 저장하면 된다. 109 | 110 | 올바른 스펙으로 토큰 발급 API를 호출하면 마침내 Access Token을 얻을 수 있다. 111 | ```shell 112 | curl -X POST http://localhost:8080/custom-uri/oauth2/token\?grant_type\=client_credentials \ 113 | --header 'Content-Type: application/x-www-form-urlencoded' \ 114 | --header 'Authorization: Basic YWFhYTpiYmJi' -v 115 | > Content-Type: application/x-www-form-urlencoded 116 | > Authorization: Basic YWFhYTpiYmJi 117 | * Mark bundle as not supporting multiuse 118 | < HTTP/1.1 200 119 | {"access_token":"eyJraWQiOiIzZTk2OGI0YS04Zjk2LTRkMjMtYjc5MS02MmYzMGRiYWE1M2MiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhYWFhIiwiYXVkIjoiYWFhYSIsIm5iZiI6MTY3Nzk1MzQzOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwiZXhwIjoxNjc3OTYwNjM5LCJpYXQiOjE2Nzc5NTM0Mzl9.BApI_joRvSMBcQE4c3U86oJxKwCTf3EGgC-6pNGQ7sL3PvZ6FF1S5sNUC9RqqV5qRtDxLVV1CL3h9Elzz-AzyuH3Dnvky-VGbbtnl01fqlvHX33ovEmLDLWR_wWwC4NXiClD1ad-jamOO4bvd_TVPj84W7-Ok9Sza74X5jlAYK-l0Zca8J-GpRhF92wr7UDCdPdde_FKk99dO3LWf-qbklQBgitnbgUYc1but-fRypKoTfa8uT0NCd8pw3OkDSLuJ8rVvbqCWH5ugHZtt0Z1ZasVnMKz9XFjkpcpifIr-zT9-g807zoCFktS0pFN5aMcWpENV30EQDvyOCr94-nRwA","token_type":"Bearer","expires_in":7199} 120 | ``` 121 | access_token 값은 JWT라서 길이가 제법 긴데 Opaque Token이였으면 많이 짧을 것이다. token_type은 Bearer, expires_in:7199초로 2시간인 것을 알 수 있다. 122 | 123 | 4. Access Token으로 API 호출 124 | ```shell 125 | curl -X GET localhost:8080/v1/users/me \ 126 | --header 'Authorization: Bearer eyJraWQiOiIzZTk2OGI0YS04Zjk2LTRkMjMtYjc5MS02MmYzMGRiYWE1M2MiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhYWFhIiwiYXVkIjoiYWFhYSIsIm5iZiI6MTY3Nzk1MzQzOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwiZXhwIjoxNjc3OTYwNjM5LCJpYXQiOjE2Nzc5NTM0Mzl9.BApI_joRvSMBcQE4c3U86oJxKwCTf3EGgC-6pNGQ7sL3PvZ6FF1S5sNUC9RqqV5qRtDxLVV1CL3h9Elzz-AzyuH3Dnvky-VGbbtnl01fqlvHX33ovEmLDLWR_wWwC4NXiClD1ad-jamOO4bvd_TVPj84W7-Ok9Sza74X5jlAYK-l0Zca8J-GpRhF92wr7UDCdPdde_FKk99dO3LWf-qbklQBgitnbgUYc1but-fRypKoTfa8uT0NCd8pw3OkDSLuJ8rVvbqCWH5ugHZtt0Z1ZasVnMKz9XFjkpcpifIr-zT9-g807zoCFktS0pFN5aMcWpENV30EQDvyOCr94-nRwA 127 | ' -v 128 | > Authorization: Bearer eyJraWQiOiIzZTk2OGI0YS04Zjk2LTRkMjMtYjc5MS02MmYzMGRiYWE1M2MiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhYWFhIiwiYXVkIjoiYWFhYSIsIm5iZiI6MTY3Nzk1MzQzOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwiZXhwIjoxNjc3OTYwNjM5LCJpYXQiOjE2Nzc5NTM0Mzl9.BApI_joRvSMBcQE4c3U86oJxKwCTf3EGgC-6pNGQ7sL3PvZ6FF1S5sNUC9RqqV5qRtDxLVV1CL3h9Elzz-AzyuH3Dnvky-VGbbtnl01fqlvHX33ovEmLDLWR_wWwC4NXiClD1ad-jamOO4bvd_TVPj84W7-Ok9Sza74X5jlAYK-l0Zca8J-GpRhF92wr7UDCdPdde_FKk99dO3LWf-qbklQBgitnbgUYc1but-fRypKoTfa8uT0NCd8pw3OkDSLuJ8rVvbqCWH5ugHZtt0Z1ZasVnMKz9XFjkpcpifIr-zT9-g807zoCFktS0pFN5aMcWpENV30EQDvyOCr94-nRwA 129 | < HTTP/1.1 200 130 | {"nickname":"traeper"}% 131 | ``` 132 | 133 | 소량의 코드만으로 OAuth 2.0 Authorization Server 구현 성공! 134 | 135 | ## Spring Authorization Framework 파헤쳐 보기 136 | 프레임워크가 동작하는 원리를 좀더 파보자. 137 | 138 | ### FilterChainProxy 중 사용된 Filter 살펴보기 139 | ![](./resources/FilterChainProxy-oauth2.png) 140 | 141 | 위 이미지는 FilterChainProxy의 filterChains 필드에 등록된 필터들을 보여준다. 142 | Spring Security가 제공하는 10개 정도의 기본 필터 외에도 OAuth 2.0 Authorization Server 구현을 위한 필터도 약 10개 정도 추가되어 총 19개나 된다. 143 | 144 | 이번 테스트에 사용된 필터는 빨갛게 칠해진 3개다. 145 | * OAuth2ClientAuthenticationFilter : Client로부터 받은 인증 요청을 처리하는 필터 146 | * ClientSecretBasicAuthenticationConverter : 테스트에 사용된 client_secret_basic Authorization 헤더에서 clientId, clientSecret을 추출한다. 147 | * ClientSecretAuthenticationProvider : 입력 받은 clientId, clientSecret을 검증한다. 148 | * OAuth2TokenEndpointFilter : 토큰 발급 endpoint 필터 149 | * OAuth2ClientCredentialsAuthenticationConverter : client_credentials 방식을 지원하는 OAuth2ClientCredentialsAuthenticationToken 토큰 생성 150 | * OAuth2ClientCredentialsAuthenticationProvider : OAuth2ClientCredentialsAuthenticationToken 토큰을 읽고 AccessToken을 생성 151 | * BearerTokenAuthenticationFilter : Bearer Token을 인증하는 필터 152 | * JwtAuthenticationProvider : jwt를 검증한다. 153 | 154 | 만약 다른 인증 방식, endpoint, 토큰 타입 등을 활용한다면 사용되는 구현체가 달라질 수 있다. 155 | 156 | ## References 157 | * The OAuth 2.0 Authorization Framework : https://www.rfc-editor.org/rfc/rfc6749 158 | * The OAuth 2.1 Authorization Framework : https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-07 159 | * 프로젝트 깃헙 링크 : https://github.com/spring-projects/spring-authorization-server 160 | * Spring Authorization Server Reference : https://docs.spring.io/spring-authorization-server/docs/current/reference/html/index.html 161 | --------------------------------------------------------------------------------