├── .gitignore ├── GoogleStyle.xml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── http └── e2e.http ├── settings.gradle └── src ├── main ├── java │ └── io │ │ └── github │ │ └── gunkim │ │ ├── Application.java │ │ ├── domain │ │ ├── Member.java │ │ ├── MemberRepository.java │ │ └── Role.java │ │ ├── endpoint │ │ └── HomeController.java │ │ └── security │ │ ├── JwtAuthenticationToken.java │ │ ├── SkipPathRequestMatcher.java │ │ ├── config │ │ ├── PasswordConfig.java │ │ └── SecurityConfig.java │ │ ├── exception │ │ ├── AuthMethodNotSupportedException.java │ │ └── JwtExpiredTokenException.java │ │ ├── filter │ │ ├── JwtTokenAuthenticationFilter.java │ │ ├── JwtTokenIssueFilter.java │ │ └── request │ │ │ └── LoginRequest.java │ │ ├── handler │ │ ├── CommonAuthenticationFailureHandler.java │ │ ├── JwtTokenIssueSuccessHandler.java │ │ └── response │ │ │ ├── ErrorResponse.java │ │ │ └── TokenResponse.java │ │ ├── provider │ │ ├── JwtAuthenticationProvider.java │ │ └── JwtTokenIssueProvider.java │ │ └── service │ │ ├── CustomUserDetailsService.java │ │ ├── TokenService.java │ │ └── dto │ │ └── TokenParserResponse.java └── resources │ └── application.yml └── test └── java └── io └── github └── gunkim └── application └── spring └── security ├── filter └── JwtTokenIssueFilterTests.java └── provider └── JwtTokenIssueProviderTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | out -------------------------------------------------------------------------------- /GoogleStyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 gunkim 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring security with JWT 2 | ![Java](https://img.shields.io/badge/Java-17-red?logo=java) 3 | ![Spring Boot](https://img.shields.io/badge/SpringBoot-3.1.2-blue?logo=ktor) 4 | ![Gradle](https://img.shields.io/badge/gradle-7.4-blue?logo=gradle) 5 | [![GitHub license](https://img.shields.io/github/license/gunkim/springboot-security-jwt)](https://github.com/gunkim/springboot-security-jwt/blob/main/LICENSE) 6 | [![GitHub stars](https://img.shields.io/github/stars/gunkim/springboot-security-jwt)](https://github.com/gunkim/springboot-security-jwt) 7 | [![GitHub issues](https://img.shields.io/github/issues/gunkim/springboot-security-jwt)](https://github.com/gunkim/springboot-security-jwt/issues) 8 | [![GitHub forks](https://img.shields.io/github/forks/gunkim/springboot-security-jwt)](https://github.com/gunkim/springboot-security-jwt/fork) 9 | 10 | 스프링 시큐리티 이해도를 높이기 위해 전부 커스텀하여 구현했으나 [Spring Security OAuth2 Resource Server](https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html) JWT 구현체를 사용하면 기본 세팅으로 더 쉽게 사용이 가능하다. 11 | 12 | 2023년 8월 6일 기준 Spring Boot 3.X.X로 마이그레이션했으니 2.X.X 버전을 참고하고 싶다면 [이 곳](https://github.com/gunkim/springboot-security-jwt/tree/ce60a09d59d2790f663233d4a67c1287ddf938b8)을 참고하면 된다. 13 | 14 | # 개요 15 | 16 | ## 로그인 시 17 | ![1](https://user-images.githubusercontent.com/45007556/104460769-dbeaa780-55f1-11eb-9149-8d54a1c89c9e.png) 18 | 19 | ## 로그인 인증 시 20 | ![image](https://user-images.githubusercontent.com/45007556/104460703-c5dce700-55f1-11eb-8931-991164f48a52.png) 21 | 22 | # AuthenticationManager는 Provider를 어떻게 할당 받을까? 23 | 스프링 시큐리티를 공부해 보면 AuthenticationManager는 AuthenticationProvider에게 실질적인 인증 처리를 위임한다고 한다. 24 | 하지만 지금까지 본 코드를 보았을 때 SecurityConfig를 통해 Provider를 등록해주는 코드는 있어도, Filter이나 AuthenticationManager에게 직접적으로 어떤 Provider를 쓸 것이라고 주입해주는 코드는 없다. 25 | ## 둘 이상의 Provider가 전달된 경우 Authentication을 가지고 판단한다. 26 | 만약 여러 개의 Provider가 등록이 되어 있을 경우, AuthenticationManager는 어떻게 어떤 Provider에게 위임할 지를 결정할까? 27 | AuthenticationManager을 구현한 ProviderManager [API 문서](https://docs.spring.io/spring-security/site/docs/4.2.15.RELEASE/apidocs/org/springframework/security/authentication/ProviderManager.html#authenticate-org.springframework.security.core.Authentication-) 를 보면 둘 이상의 Provider가 등록된 경우 Authentication을 처리할 수 있는 Provider를 찾아 할당한다고 한다. 28 | ## 로그인 처리 시 Filter-Provider 코드 29 | ```java 30 | UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()); 31 | return this.getAuthenticationManager().authenticate(token); 32 | ``` 33 | ```java 34 | @Override 35 | public boolean supports(Class authentication) { 36 | return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); 37 | } 38 | ``` 39 | ## JWT 토큰 인증 시 Filter-Provider 코드 40 | 41 | ```java 42 | return getAuthenticationManager().authenticate(new JwtAuthenticationToken(claimsJws)); 43 | ``` 44 | 45 | ```java 46 | @Override 47 | public boolean supports(Class authentication) { 48 | return (JwtAuthenticationToken.class.isAssignableFrom(authentication)); 49 | } 50 | ``` 51 | 해당 소스들을 보면 supports에 지원하는 토큰 타입을 명시해 놓았다. 그래서 이것을 가지고 필터에서 전달하는 토큰 타입을 확인하여 Provider를 매칭해준다는 것을 알 수 있다. 52 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'idea' 4 | id 'org.springframework.boot' version '3.1.2' 5 | id 'io.spring.dependency-management' version '1.0.13.RELEASE' 6 | } 7 | 8 | group = 'io.github.gunkim' 9 | version = '1.0.0' 10 | 11 | sourceCompatibility = '17' 12 | targetCompatibility = '17' 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation 'org.springframework.boot:spring-boot-starter-web' 20 | implementation 'org.springframework.boot:spring-boot-starter-security' 21 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | testImplementation 'org.assertj:assertj-core:3.24.2' 24 | 25 | runtimeOnly 'com.h2database:h2:2.2.220' 26 | 27 | implementation 'io.jsonwebtoken:jjwt-api:0.11.5' 28 | implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' 29 | runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' 30 | 31 | implementation 'org.projectlombok:lombok:1.18.22' 32 | annotationProcessor 'org.projectlombok:lombok:1.18.22' 33 | } 34 | 35 | test { 36 | useJUnitPlatform() 37 | } 38 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gunkim/spring-security-jwt-sample/557aceb30c57fc005ac8c0d1051da9cac1d001be/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://services.gradle.org/distributions/gradle-8.2.1-bin.zip 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStorePath=wrapper/dists 5 | zipStoreBase=GRADLE_USER_HOME 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or 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 UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /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 Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /http/e2e.http: -------------------------------------------------------------------------------- 1 | # 테스트용 계정 정보 2 | # user 권한 - 3 | # username: user 4 | # password: 1234 5 | 6 | # admin 권한 - 7 | # username: admin 8 | # password: 1234 9 | 10 | ### 토큰 발급(로그인) 11 | POST localhost:8080/api/auth/login 12 | 13 | { 14 | "username":"admin", 15 | "password":"1234" 16 | } 17 | 18 | ### 어드민 권한 엔드포인트 19 | GET localhost:8080/api/say/admin 20 | Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInJvbGVzIjpbIlJPTEVfQURNSU4iXSwiaXNzIjoiZ3Vua2ltIiwiaWF0IjoxNjgxMjA1NDg3LCJleHAiOjE3ODkyMDU0ODd9.gcngjRiSQTPqr7H-vFpY-dV6y2vQhimBwEDMSgcLXes 21 | 22 | ### 유저 권한 엔드포인트 23 | GET localhost:8080/api/say/user 24 | Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndW5raW0iLCJyb2xlcyI6WyJST0xFX1VTRVIiXSwiaXNzIjoiZ3Vua2ltIiwiaWF0IjoxNjgxMjAzODUzLCJleHAiOjE3ODkyMDM4NTN9.voirq_vk6FUxmQAXjwpPV3XwoZ6yaBi6Se-aV75AIjQ 25 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'springboot-security-jwt' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/Application.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim; 2 | 3 | import io.github.gunkim.domain.Member; 4 | import io.github.gunkim.domain.MemberRepository; 5 | import io.github.gunkim.domain.Role; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | 12 | @SpringBootApplication 13 | public class Application { 14 | public static void main(String[] args) { 15 | SpringApplication.run(Application.class, args); 16 | } 17 | 18 | @Bean 19 | public CommandLineRunner runner(MemberRepository memberRepository, PasswordEncoder passwordEncoder) { 20 | return __ -> { 21 | memberRepository.save(new Member("user", passwordEncoder.encode("1234"), Role.USER)); 22 | memberRepository.save(new Member("admin", passwordEncoder.encode("1234"), Role.ADMIN)); 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/domain/Member.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.domain; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.AccessLevel; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.experimental.Accessors; 9 | 10 | @Entity 11 | @Getter 12 | @AllArgsConstructor 13 | @Accessors(fluent = true) 14 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 15 | public class Member { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.IDENTITY) 18 | private long id; 19 | 20 | private String username; 21 | 22 | private String password; 23 | 24 | @Enumerated(EnumType.STRING) 25 | private Role role; 26 | 27 | public Member(String username, String password, Role role) { 28 | this.username = username; 29 | this.password = password; 30 | this.role = role; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/domain/MemberRepository.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.domain; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import java.util.Optional; 6 | 7 | public interface MemberRepository extends JpaRepository { 8 | Optional findByUsername(String username); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/domain/Role.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.domain; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.experimental.Accessors; 6 | 7 | import java.util.Arrays; 8 | 9 | @Getter 10 | @RequiredArgsConstructor 11 | @Accessors(fluent = true) 12 | public enum Role { 13 | USER("일반 사용자", "ROLE_USER"), 14 | ADMIN("관리자", "ROLE_ADMIN"); 15 | 16 | private final String title; 17 | private final String value; 18 | 19 | public static Role of(String value) { 20 | return Arrays.stream(values()) 21 | .filter(role -> role.value.equals(value)) 22 | .findFirst() 23 | .orElseThrow(() -> new IllegalArgumentException("잘못된 권한입니다.")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/endpoint/HomeController.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.endpoint; 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 | @RestController 8 | @RequestMapping("/api/say") 9 | public class HomeController { 10 | @GetMapping("/admin") 11 | public String adminHello() { 12 | return "Hello!"; 13 | } 14 | 15 | @GetMapping("/user") 16 | public String userHello() { 17 | return "Hello!"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/JwtAuthenticationToken.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security; 2 | 3 | import org.springframework.security.authentication.AbstractAuthenticationToken; 4 | import org.springframework.security.core.GrantedAuthority; 5 | 6 | import java.util.Collection; 7 | import java.util.Objects; 8 | 9 | public class JwtAuthenticationToken extends AbstractAuthenticationToken { 10 | private final String jwtToken; 11 | private final String username; 12 | 13 | public JwtAuthenticationToken(String jwtToken) { 14 | super(null); 15 | this.setAuthenticated(false); 16 | this.jwtToken = jwtToken; 17 | this.username = null; 18 | } 19 | 20 | public JwtAuthenticationToken(String username, Collection authorities) { 21 | super(authorities); 22 | this.eraseCredentials(); 23 | super.setAuthenticated(true); 24 | this.username = username; 25 | this.jwtToken = null; 26 | } 27 | 28 | @Override 29 | public String getCredentials() { 30 | return this.jwtToken; 31 | } 32 | 33 | @Override 34 | public String getPrincipal() { 35 | return username; 36 | } 37 | 38 | @Override 39 | public boolean equals(Object o) { 40 | if (this == o) { 41 | return true; 42 | } 43 | if (o == null || getClass() != o.getClass()) { 44 | return false; 45 | } 46 | if (!super.equals(o)) { 47 | return false; 48 | } 49 | JwtAuthenticationToken that = (JwtAuthenticationToken) o; 50 | return Objects.equals(jwtToken, that.jwtToken) && Objects.equals(username, that.username); 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | return Objects.hash(super.hashCode(), jwtToken, username); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/SkipPathRequestMatcher.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security; 2 | 3 | import jakarta.servlet.http.HttpServletRequest; 4 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 5 | import org.springframework.security.web.util.matcher.OrRequestMatcher; 6 | import org.springframework.security.web.util.matcher.RequestMatcher; 7 | 8 | import java.util.List; 9 | 10 | import static java.util.stream.Collectors.toList; 11 | 12 | public class SkipPathRequestMatcher implements RequestMatcher { 13 | private final OrRequestMatcher matchers; 14 | private final RequestMatcher processingMatcher; 15 | 16 | public SkipPathRequestMatcher(List pathsToSkip, String processingPath) { 17 | if (pathsToSkip == null) { 18 | throw new IllegalArgumentException("pathsToSkip cannot be null"); 19 | } 20 | this.matchers = new OrRequestMatcher(pathsToSkip.stream().map(AntPathRequestMatcher::new).collect(toList())); 21 | this.processingMatcher = new AntPathRequestMatcher(processingPath); 22 | } 23 | 24 | @Override 25 | public boolean matches(HttpServletRequest request) { 26 | if (matchers.matches(request)) { 27 | return false; 28 | } 29 | return processingMatcher.matches(request); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/config/PasswordConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | import org.springframework.security.crypto.password.PasswordEncoder; 7 | 8 | @Configuration 9 | public class PasswordConfig { 10 | @Bean 11 | public PasswordEncoder passwordEncoder() { 12 | return new BCryptPasswordEncoder(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import io.github.gunkim.security.SkipPathRequestMatcher; 5 | import io.github.gunkim.security.filter.JwtTokenAuthenticationFilter; 6 | import io.github.gunkim.security.filter.JwtTokenIssueFilter; 7 | import io.github.gunkim.security.provider.JwtAuthenticationProvider; 8 | import io.github.gunkim.security.provider.JwtTokenIssueProvider; 9 | import io.github.gunkim.domain.Role; 10 | import lombok.RequiredArgsConstructor; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.security.authentication.AuthenticationManager; 14 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 15 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 16 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 17 | import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 18 | import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; 19 | import org.springframework.security.config.http.SessionCreationPolicy; 20 | import org.springframework.security.web.SecurityFilterChain; 21 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 22 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 23 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 24 | 25 | import java.util.List; 26 | 27 | @Configuration 28 | @EnableWebSecurity 29 | @RequiredArgsConstructor 30 | public class SecurityConfig { 31 | 32 | public static final String AUTHENTICATION_URL = "/api/auth/login"; 33 | public static final String API_ROOT_URL = "/api/**"; 34 | 35 | private final AuthenticationSuccessHandler successHandler; 36 | private final AuthenticationFailureHandler failureHandler; 37 | 38 | private final ObjectMapper objectMapper; 39 | 40 | @Bean 41 | public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) 42 | throws Exception { 43 | return http.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 44 | .csrf(AbstractHttpConfigurer::disable) 45 | .authorizeHttpRequests(this::authorizeHttpRequests) 46 | .addFilterBefore(jwtTokenIssueFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class) 47 | .addFilterBefore(jwtTokenAuthenticationFilter(List.of(AUTHENTICATION_URL), authenticationManager), UsernamePasswordAuthenticationFilter.class) 48 | .build(); 49 | } 50 | 51 | @Bean 52 | public AuthenticationManager authenticationManager(HttpSecurity http, JwtTokenIssueProvider jwtTokenIssueProvider, 53 | JwtAuthenticationProvider jwtAuthenticationProvider) throws Exception { 54 | var authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); 55 | authenticationManagerBuilder.authenticationProvider(jwtAuthenticationProvider); 56 | authenticationManagerBuilder.authenticationProvider(jwtTokenIssueProvider); 57 | 58 | return authenticationManagerBuilder.build(); 59 | } 60 | 61 | private void authorizeHttpRequests(AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry configurer) { 62 | configurer 63 | .requestMatchers("/api/say/admin").hasAnyRole(Role.ADMIN.name()) 64 | .requestMatchers("/api/say/user").hasAnyRole(Role.USER.name()); 65 | } 66 | 67 | private JwtTokenIssueFilter jwtTokenIssueFilter(AuthenticationManager authenticationManager) { 68 | var filter = new JwtTokenIssueFilter(AUTHENTICATION_URL, objectMapper, successHandler, failureHandler); 69 | filter.setAuthenticationManager(authenticationManager); 70 | 71 | return filter; 72 | } 73 | 74 | private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter(List pathsToSkip, 75 | AuthenticationManager authenticationManager) { 76 | var matcher = new SkipPathRequestMatcher(pathsToSkip, API_ROOT_URL); 77 | var filter = new JwtTokenAuthenticationFilter(matcher, failureHandler); 78 | filter.setAuthenticationManager(authenticationManager); 79 | 80 | return filter; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/exception/AuthMethodNotSupportedException.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.exception; 2 | 3 | import org.springframework.security.authentication.AuthenticationServiceException; 4 | 5 | public class AuthMethodNotSupportedException extends AuthenticationServiceException { 6 | public AuthMethodNotSupportedException(String msg) { 7 | super(msg); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/exception/JwtExpiredTokenException.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | 5 | public class JwtExpiredTokenException extends AuthenticationException { 6 | public JwtExpiredTokenException(String msg, Throwable t) { 7 | super(msg, t); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/filter/JwtTokenAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.filter; 2 | 3 | import io.github.gunkim.security.JwtAuthenticationToken; 4 | import jakarta.servlet.FilterChain; 5 | import jakarta.servlet.ServletException; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.security.authentication.BadCredentialsException; 10 | import org.springframework.security.core.Authentication; 11 | import org.springframework.security.core.AuthenticationException; 12 | import org.springframework.security.core.context.SecurityContext; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 15 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 16 | import org.springframework.security.web.util.matcher.RequestMatcher; 17 | 18 | import java.io.IOException; 19 | 20 | import static java.util.Objects.isNull; 21 | 22 | public class JwtTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter { 23 | public JwtTokenAuthenticationFilter(RequestMatcher matcher, AuthenticationFailureHandler failureHandler) { 24 | super(matcher); 25 | this.setAuthenticationFailureHandler(failureHandler); 26 | } 27 | 28 | @Override 29 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 30 | throws AuthenticationException { 31 | String tokenPayload = extractToken(request.getHeader(HttpHeaders.AUTHORIZATION)); 32 | 33 | return getAuthenticationManager().authenticate(new JwtAuthenticationToken(tokenPayload)); 34 | } 35 | 36 | @Override 37 | protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, 38 | Authentication authentication) throws IOException, ServletException { 39 | SecurityContext context = SecurityContextHolder.createEmptyContext(); 40 | context.setAuthentication(authentication); 41 | 42 | SecurityContextHolder.setContext(context); 43 | chain.doFilter(request, response); 44 | } 45 | 46 | @Override 47 | protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, 48 | AuthenticationException authenticationException) throws IOException, ServletException { 49 | SecurityContextHolder.clearContext(); 50 | getFailureHandler().onAuthenticationFailure(request, response, authenticationException); 51 | } 52 | 53 | private String extractToken(String tokenPayload) { 54 | if (isNull(tokenPayload) || !tokenPayload.startsWith("Bearer ")) { 55 | throw new BadCredentialsException("Invalid token"); 56 | } 57 | return tokenPayload.replace("Bearer ", ""); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/filter/JwtTokenIssueFilter.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.filter; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import io.github.gunkim.security.exception.AuthMethodNotSupportedException; 5 | import io.github.gunkim.security.filter.request.LoginRequest; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 10 | import org.springframework.security.core.Authentication; 11 | import org.springframework.security.core.AuthenticationException; 12 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 13 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 14 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 15 | 16 | import java.io.IOException; 17 | 18 | public class JwtTokenIssueFilter extends AbstractAuthenticationProcessingFilter { 19 | private final ObjectMapper objectMapper; 20 | 21 | public JwtTokenIssueFilter(String defaultFilterProcessesUrl, ObjectMapper objectMapper, 22 | AuthenticationSuccessHandler authenticationSuccessHandler, 23 | AuthenticationFailureHandler authenticationFailureHandler) { 24 | super(defaultFilterProcessesUrl); 25 | this.objectMapper = objectMapper; 26 | this.setAuthenticationSuccessHandler(authenticationSuccessHandler); 27 | this.setAuthenticationFailureHandler(authenticationFailureHandler); 28 | } 29 | 30 | @Override 31 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 32 | throws AuthenticationException, IOException { 33 | if (!isPostMethod(request)) { 34 | throw new AuthMethodNotSupportedException("Authentication method not supported"); 35 | } 36 | 37 | var loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class); 38 | var token = UsernamePasswordAuthenticationToken.unauthenticated(loginRequest.username(), loginRequest.password()); 39 | 40 | return this.getAuthenticationManager().authenticate(token); 41 | } 42 | 43 | private boolean isPostMethod(HttpServletRequest request) { 44 | return HttpMethod.POST.name().equals(request.getMethod()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/filter/request/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.filter.request; 2 | 3 | public record LoginRequest(String username, String password) { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/handler/CommonAuthenticationFailureHandler.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.handler; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import io.github.gunkim.security.handler.response.ErrorResponse; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import jakarta.servlet.http.HttpServletResponse; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.io.IOException; 15 | 16 | @Component 17 | @RequiredArgsConstructor 18 | public class CommonAuthenticationFailureHandler implements AuthenticationFailureHandler { 19 | private final ObjectMapper objectMapper; 20 | 21 | @Override 22 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 23 | AuthenticationException exception) throws IOException { 24 | response.setStatus(HttpStatus.UNAUTHORIZED.value()); 25 | response.setContentType(MediaType.APPLICATION_JSON_VALUE); 26 | response.setCharacterEncoding("UTF-8"); 27 | 28 | objectMapper.writeValue(response.getWriter(), new ErrorResponse(exception.getMessage())); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/handler/JwtTokenIssueSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.handler; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import io.github.gunkim.security.handler.response.TokenResponse; 5 | import io.github.gunkim.security.service.TokenService; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.web.WebAttributes; 14 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 15 | import org.springframework.stereotype.Component; 16 | 17 | import java.io.IOException; 18 | 19 | import static java.util.Objects.isNull; 20 | 21 | @Component 22 | @RequiredArgsConstructor 23 | public class JwtTokenIssueSuccessHandler implements AuthenticationSuccessHandler { 24 | private final ObjectMapper objectMapper; 25 | private final TokenService tokenService; 26 | 27 | @Override 28 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 29 | Authentication authentication) throws IOException { 30 | onAuthenticationSuccess(request, response, (UsernamePasswordAuthenticationToken) authentication); 31 | } 32 | 33 | private void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 34 | UsernamePasswordAuthenticationToken authentication) throws IOException { 35 | String username = authentication.getPrincipal().toString(); 36 | var authorities = authentication.getAuthorities(); 37 | 38 | var tokenResponse = new TokenResponse(tokenService.createToken(username, authorities)); 39 | 40 | response.setStatus(HttpStatus.OK.value()); 41 | response.setContentType(MediaType.APPLICATION_JSON_VALUE); 42 | objectMapper.writeValue(response.getWriter(), tokenResponse); 43 | 44 | var session = request.getSession(false); 45 | if (!isNull(session)) { 46 | session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/handler/response/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.handler.response; 2 | 3 | public record ErrorResponse(String message) { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/handler/response/TokenResponse.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.handler.response; 2 | 3 | public record TokenResponse(String token) { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/provider/JwtAuthenticationProvider.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.provider; 2 | 3 | import io.github.gunkim.security.JwtAuthenticationToken; 4 | import io.github.gunkim.security.service.TokenService; 5 | import io.github.gunkim.security.service.dto.TokenParserResponse; 6 | import io.github.gunkim.domain.Role; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.security.authentication.AuthenticationProvider; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.util.List; 15 | 16 | @Component 17 | @RequiredArgsConstructor 18 | public class JwtAuthenticationProvider implements AuthenticationProvider { 19 | private final TokenService tokenService; 20 | 21 | @Override 22 | public Authentication authenticate(Authentication authentication) throws AuthenticationException { 23 | return authenticate((JwtAuthenticationToken) authentication); 24 | } 25 | 26 | @Override 27 | public boolean supports(Class authentication) { 28 | return (JwtAuthenticationToken.class.isAssignableFrom(authentication)); 29 | } 30 | 31 | private Authentication authenticate(JwtAuthenticationToken authentication) throws AuthenticationException { 32 | String jwtToken = authentication.getCredentials(); 33 | TokenParserResponse response = tokenService.parserToken(jwtToken); 34 | 35 | return new JwtAuthenticationToken(response.username(), authorities(response)); 36 | } 37 | 38 | private List authorities(TokenParserResponse response) { 39 | return response.roles().stream() 40 | .map(Role::value) 41 | .map(SimpleGrantedAuthority::new) 42 | .toList(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/provider/JwtTokenIssueProvider.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.provider; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.security.authentication.AuthenticationProvider; 5 | import org.springframework.security.authentication.BadCredentialsException; 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.AuthenticationException; 9 | import org.springframework.security.core.GrantedAuthority; 10 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.stereotype.Component; 15 | 16 | import java.util.List; 17 | 18 | @Component 19 | @RequiredArgsConstructor 20 | public class JwtTokenIssueProvider implements AuthenticationProvider { 21 | private final PasswordEncoder passwordEncoder; 22 | private final UserDetailsService userDetailsService; 23 | 24 | @Override 25 | public Authentication authenticate(Authentication authentication) throws AuthenticationException { 26 | var username = (String) authentication.getPrincipal(); 27 | var password = (String) authentication.getCredentials(); 28 | 29 | return authenticate(username, password); 30 | } 31 | 32 | @Override 33 | public boolean supports(Class authentication) { 34 | return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); 35 | } 36 | 37 | private UsernamePasswordAuthenticationToken authenticate(String username, String password) { 38 | UserDetails user = userDetailsService.loadUserByUsername(username); 39 | if (!passwordEncoder.matches(password, user.getPassword())) { 40 | throw new BadCredentialsException("인증 실패. username or password 불일치"); 41 | } 42 | 43 | return UsernamePasswordAuthenticationToken.authenticated(user.getUsername(), null, authorities(user)); 44 | } 45 | 46 | private List authorities(UserDetails user) { 47 | return user.getAuthorities().stream() 48 | .map(GrantedAuthority::getAuthority) 49 | .map(SimpleGrantedAuthority::new) 50 | .toList(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.service; 2 | 3 | import io.github.gunkim.domain.MemberRepository; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | import org.springframework.security.core.userdetails.User; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.List; 13 | 14 | @Service 15 | @RequiredArgsConstructor 16 | public class CustomUserDetailsService implements UserDetailsService { 17 | private final MemberRepository memberRepository; 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 21 | var member = memberRepository.findByUsername(username) 22 | .orElseThrow(() -> new UsernameNotFoundException("해당 유저를 찾을 수 없습니다. username: %s".formatted(username))); 23 | 24 | var roles = List.of(new SimpleGrantedAuthority(member.role().value())); 25 | return new User(member.username(), member.password(), roles); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/service/TokenService.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.service; 2 | 3 | import io.github.gunkim.security.exception.JwtExpiredTokenException; 4 | import io.github.gunkim.security.service.dto.TokenParserResponse; 5 | import io.github.gunkim.domain.Role; 6 | import io.jsonwebtoken.*; 7 | import io.jsonwebtoken.security.Keys; 8 | import io.jsonwebtoken.security.SignatureException; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.security.authentication.BadCredentialsException; 11 | import org.springframework.security.core.GrantedAuthority; 12 | import org.springframework.stereotype.Service; 13 | 14 | import javax.crypto.SecretKey; 15 | import java.time.LocalDateTime; 16 | import java.time.ZoneId; 17 | import java.util.Collection; 18 | import java.util.Date; 19 | import java.util.List; 20 | 21 | @Service 22 | public class TokenService { 23 | private static final String AUTHORITIES_KEY = "roles"; 24 | 25 | private final SecretKey key; 26 | private final long expirationTime; 27 | private final String issuer; 28 | 29 | public TokenService(@Value("${jwt.token.secret-key}") String key, 30 | @Value("${jwt.token.expTime}") long expirationTime, @Value("${jwt.token.issuer}") String issuer) { 31 | this.key = Keys.hmacShaKeyFor(key.getBytes()); 32 | this.expirationTime = expirationTime; 33 | this.issuer = issuer; 34 | } 35 | 36 | public String createToken(String username, Collection authorities) { 37 | LocalDateTime issuedAt = LocalDateTime.now(); 38 | LocalDateTime expiredAt = issuedAt.plusMinutes(expirationTime); 39 | 40 | return Jwts.builder() 41 | .addClaims(createClaims(username, authorities)) 42 | .setIssuer(issuer) 43 | .setIssuedAt(toDate(issuedAt)) 44 | .setExpiration(toDate(expiredAt)) 45 | .signWith(key) 46 | .compact(); 47 | } 48 | 49 | public TokenParserResponse parserToken(String token) throws BadCredentialsException, JwtExpiredTokenException { 50 | try { 51 | return tokenParserResponse( 52 | Jwts.parserBuilder() 53 | .setSigningKey(key) 54 | .build() 55 | .parseClaimsJws(token)); 56 | } catch (SignatureException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException ex) { 57 | throw new BadCredentialsException("Invalid JWT token", ex); 58 | } catch (ExpiredJwtException expiredEx) { 59 | throw new JwtExpiredTokenException("JWT Token expired", expiredEx); 60 | } 61 | } 62 | 63 | @SuppressWarnings("unchecked") 64 | private TokenParserResponse tokenParserResponse(Jws claimsJws) { 65 | String username = claimsJws.getBody().getSubject(); 66 | List roles = claimsJws.getBody().get(AUTHORITIES_KEY, List.class); 67 | 68 | return new TokenParserResponse(username, roles.stream().map(Role::of).toList()); 69 | } 70 | 71 | private Claims createClaims(String username, Collection authorities) { 72 | Claims claims = Jwts.claims().setSubject(username); 73 | claims.put(AUTHORITIES_KEY, authorities.stream().map(Object::toString).toList()); 74 | 75 | return claims; 76 | } 77 | 78 | private Date toDate(LocalDateTime dateTime) { 79 | return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/io/github/gunkim/security/service/dto/TokenParserResponse.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.security.service.dto; 2 | 3 | import io.github.gunkim.domain.Role; 4 | 5 | import java.util.List; 6 | 7 | public record TokenParserResponse(String username, List roles) { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | jwt: 2 | token: 3 | secret-key: "E12RM8Wca/SdQmJ9eAUZded/PtgNkc8btKaRrBrKSQc=" 4 | expTime: 1800000 5 | issuer: "gunkim" 6 | spring: 7 | jpa: 8 | open-in-view: false 9 | -------------------------------------------------------------------------------- /src/test/java/io/github/gunkim/application/spring/security/filter/JwtTokenIssueFilterTests.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.application.spring.security.filter; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 5 | import static org.junit.jupiter.api.Assertions.assertAll; 6 | import static org.mockito.ArgumentMatchers.any; 7 | import static org.mockito.Mockito.when; 8 | 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import io.github.gunkim.application.spring.security.exception.AuthMethodNotSupportedException; 11 | import io.github.gunkim.application.spring.security.filter.request.LoginRequest; 12 | import java.io.IOException; 13 | import java.util.List; 14 | import org.junit.jupiter.api.BeforeEach; 15 | import org.junit.jupiter.api.Test; 16 | import org.junit.jupiter.api.extension.ExtendWith; 17 | import org.junit.jupiter.params.ParameterizedTest; 18 | import org.junit.jupiter.params.provider.ValueSource; 19 | import org.mockito.Mock; 20 | import org.mockito.junit.jupiter.MockitoExtension; 21 | import org.springframework.mock.web.MockHttpServletRequest; 22 | import org.springframework.security.authentication.AuthenticationManager; 23 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 24 | import org.springframework.security.core.Authentication; 25 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 26 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 27 | 28 | @ExtendWith(MockitoExtension.class) 29 | class JwtTokenIssueFilterTests { 30 | @Mock 31 | private AuthenticationManager authenticationManager; 32 | @Mock 33 | private AuthenticationSuccessHandler authenticationSuccessHandler; 34 | @Mock 35 | private AuthenticationFailureHandler authenticationFailureHandler; 36 | private JwtTokenIssueFilter sut; 37 | 38 | @BeforeEach 39 | void setup() { 40 | sut = new JwtTokenIssueFilter( 41 | "/login", 42 | new ObjectMapper(), 43 | authenticationSuccessHandler, 44 | authenticationFailureHandler 45 | ); 46 | sut.setAuthenticationManager(authenticationManager); 47 | } 48 | 49 | @ParameterizedTest 50 | @ValueSource(strings = {"GET", "PUT", "DELETE"}) 51 | void Http_Method가_POST가_아니라면_예외가_발생한다(String method) { 52 | var request = new MockHttpServletRequest(); 53 | request.setMethod(method); 54 | 55 | assertThatThrownBy(() -> sut.attemptAuthentication(request, null)) 56 | .isInstanceOf(AuthMethodNotSupportedException.class) 57 | .hasMessage("Authentication method not supported"); 58 | } 59 | 60 | @Test 61 | void 인증된_Authentication을_반환한다() throws IOException { 62 | LoginRequest loginRequest = new LoginRequest("gunkim", "1234"); 63 | 64 | var request = new MockHttpServletRequest(); 65 | request.setMethod("POST"); 66 | request.setContent(new ObjectMapper().writeValueAsBytes(loginRequest)); 67 | 68 | when(authenticationManager.authenticate(any(Authentication.class))) 69 | .thenReturn(new UsernamePasswordAuthenticationToken("gunkim", null, List.of())); 70 | 71 | var certedAuthentication = sut.attemptAuthentication(request, null); 72 | 73 | assertAll( 74 | () -> assertThat(certedAuthentication).isNotNull(), 75 | () -> assertThat(certedAuthentication.getPrincipal()).isEqualTo("gunkim"), 76 | () -> assertThat(certedAuthentication.isAuthenticated()).isTrue() 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/io/github/gunkim/application/spring/security/provider/JwtTokenIssueProviderTests.java: -------------------------------------------------------------------------------- 1 | package io.github.gunkim.application.spring.security.provider; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.junit.jupiter.api.Assertions.assertAll; 5 | import static org.mockito.Mockito.when; 6 | 7 | import java.util.List; 8 | import org.junit.jupiter.api.Test; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.mockito.InjectMocks; 11 | import org.mockito.Mock; 12 | import org.mockito.junit.jupiter.MockitoExtension; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 16 | import org.springframework.security.core.userdetails.User; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.crypto.password.PasswordEncoder; 19 | 20 | @ExtendWith(MockitoExtension.class) 21 | class JwtTokenIssueProviderTests { 22 | @Mock 23 | private PasswordEncoder passwordEncoder; 24 | @Mock 25 | private UserDetailsService userDetailsService; 26 | 27 | @InjectMocks 28 | private JwtTokenIssueProvider sut; 29 | 30 | @Test 31 | void 인증에_성공한다() { 32 | var request = new UsernamePasswordAuthenticationToken("gunkim", "1234"); 33 | var user = new User("gunkim", "encoded password 1234", List.of(new SimpleGrantedAuthority("ROLE_USER"))); 34 | 35 | when(userDetailsService.loadUserByUsername((String) request.getPrincipal())) 36 | .thenReturn(user); 37 | when(passwordEncoder.matches((CharSequence) request.getCredentials(), user.getPassword())) 38 | .thenReturn(true); 39 | 40 | UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) sut.authenticate( 41 | request); 42 | 43 | assertAll( 44 | () -> assertThat(authentication.getPrincipal()).isEqualTo("gunkim"), 45 | () -> assertThat(authentication.getCredentials()).isNull(), 46 | () -> assertThat(authentication.getAuthorities()).containsExactly(new SimpleGrantedAuthority("ROLE_USER")) 47 | ); 48 | } 49 | 50 | @Test 51 | void 검증_대상일_경우_true를_반환한다() { 52 | boolean isSupported = sut.supports(UsernamePasswordAuthenticationToken.class); 53 | 54 | assertThat(isSupported).isTrue(); 55 | } 56 | 57 | @Test 58 | void 검증_대상이_아닐_경우_false를_반환한다() { 59 | boolean isSupported = sut.supports(Authentication.class); 60 | 61 | assertThat(isSupported).isFalse(); 62 | } 63 | } 64 | --------------------------------------------------------------------------------