Merge pull request #6 from banjjoknim/security-jwt

spring-security JWT 예제 코드 추가
This commit is contained in:
Colt
2022-04-04 00:17:21 +09:00
committed by GitHub
22 changed files with 694 additions and 34 deletions

View File

@@ -24,6 +24,10 @@ dependencies {
// OAuth2 로그인을 위해 추가. spring-boot-starter-security 의존성이 있어도 기본적으로 추가되지 않기 때문.
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
// https://mvnrepository.com/artifact/com.auth0/java-jwt
// JWT 사용을 위해 라이브러리 추가. 2022.03.25 기준 최신 바로 전 버전.
implementation("com.auth0:java-jwt:3.18.3")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

View File

@@ -1,21 +0,0 @@
package com.banjjoknim.playground.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// @EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login");
}
}

View File

@@ -1,8 +1,8 @@
package com.banjjoknim.playground.config.security
package com.banjjoknim.playground.daooauth.config.security
import com.banjjoknim.playground.domain.auth.OAuth2Type
import com.banjjoknim.playground.domain.user.User
import com.banjjoknim.playground.domain.user.UserRepository
import com.banjjoknim.playground.daooauth.domain.auth.OAuth2Type
import com.banjjoknim.playground.daooauth.domain.user.User
import com.banjjoknim.playground.daooauth.domain.user.UserRepository
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
@@ -41,9 +41,18 @@ import org.springframework.stereotype.Service
*
* OAuth2는 여러가지 방식이 있다. Authorization Code Grant Type 방식 등등..
*
* `@EnableGlobalMethodSecurity` 어노테이션을 사용하면 스프링 시큐리티 관련 특정 어노테이션에 대한 활성화 설정을 있다.
* [spring-security-method-security](https://www.baeldung.com/spring-security-method-security) 참고.
*
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties
* @see org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter
* @see org.springframework.security.config.oauth2.client.CommonOAuth2Provider
* @see org.springframework.security.access.prepost.PreAuthorize
* @see org.springframework.security.access.prepost.PostAuthorize
* @see org.springframework.security.access.prepost.PreFilter
* @see org.springframework.security.access.prepost.PostFilter
* @see org.springframework.security.access.annotation.Secured
* @see javax.annotation.security.RolesAllowed
*/
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록되도록 해준다.
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) // 스프링 시큐리티 관련 특정 어노테이션에 대한 활성화 설정을 할 수 있다.
@@ -147,7 +156,7 @@ class PrincipalDetails(
}
// 해당 User 의 권한을 반환하는 함수
override fun getAuthorities(): Collection<out GrantedAuthority> {
override fun getAuthorities(): Collection<GrantedAuthority> {
return listOf(GrantedAuthority { user.role })
}

View File

@@ -1,4 +1,4 @@
package com.banjjoknim.playground.domain.auth
package com.banjjoknim.playground.daooauth.domain.auth
enum class OAuth2Type(
private val provider: String,

View File

@@ -1,4 +1,4 @@
package com.banjjoknim.playground.domain.user
package com.banjjoknim.playground.daooauth.domain.user
import javax.persistence.Entity
import javax.persistence.GeneratedValue

View File

@@ -1,7 +1,7 @@
package com.banjjoknim.playground.domain.user
package com.banjjoknim.playground.daooauth.domain.user
import com.banjjoknim.playground.config.security.PrincipalDetails
import com.banjjoknim.playground.config.security.PrincipalOAuth2UserService
import com.banjjoknim.playground.daooauth.config.security.PrincipalDetails
import com.banjjoknim.playground.daooauth.config.security.PrincipalOAuth2UserService
import org.springframework.security.core.Authentication
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.userdetails.UserDetails

View File

@@ -1,4 +1,4 @@
package com.banjjoknim.playground.domain.user
package com.banjjoknim.playground.daooauth.domain.user
import org.springframework.data.jpa.repository.JpaRepository

View File

@@ -0,0 +1,67 @@
package com.banjjoknim.playground.jwt.config.filter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
/**
* ```kotlin
* corsConfiguration.allowCredentials = true
*
* user credentials 을 허용한다. 즉, 서버가 응답을 할 때 json 을 자바스크립트에서 처리할 수 있게(응답을 받을 수 있게) 할건지 말건지를 설정한다.
* 만약 false 로 설정할 경우, 자바스크립트로 어떤 요청을 했을 때 서버로부터 응답이 오지 않는다.
* ```
*
* ```kotlin
* corsConfiguration.addAllowedOrigin("*")
*
* 모든 IP에 응답을 허용한다는 설정.
* ```
*
* ```kotlin
* corsConfiguration.addAllowedHeader("*")
*
* 모든 Header에 응답을 허용한다는 설정.
* ```
*
* ```kotlin
* corsConfiguration.addAllowedMethod("*")
*
* 모든 HTTP METHOD 요청을 허용한다는 설정.
* ```
*
* CorsFilter 대신 `@CrossOrigin` 어노테이션은 사용하더라도 Security 인증이 필요한 요청은 전부 거부된다.
*
* `@CrossOrigin` 어노테이션은 인증이 필요하지 않은 요청만 허용해준다. 예를 들어, 로그인을 해야만 할 수 있는 요청들은 모두 거부된다.
*
* 인증이 필요한 경우는 CorsFilter 를 Security Filter 에 등록해주어야 하고, 인증이 필요 없는 경우는 `@CrossOrigin` 어노테이션을 사용할 수 있다.
*
* @see org.springframework.web.cors.CorsConfiguration
* @see org.springframework.web.cors.UrlBasedCorsConfigurationSource
* @see org.springframework.web.filter.CorsFilter
* @see org.springframework.web.bind.annotation.CrossOrigin
*/
@Configuration
class CorsFilterConfiguration {
/**
* Spring 에서 관리하는 Bean 으로 등록한 CorsFilter 를 Security Filter 에 등록해주어야 한다.
*
* 단순히 Bean 으로만 등록해서는 동작하지 않는다.
*
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
*/
@Bean
fun corsFilter(): CorsFilter {
val corsConfigurationSource = UrlBasedCorsConfigurationSource() // URL 을 이용한 CORS 설정을 담아두는 객체.
val corsConfiguration = CorsConfiguration() // CORS 설정 객체.
corsConfiguration.allowCredentials = true
corsConfiguration.addAllowedOrigin("*")
corsConfiguration.addAllowedHeader("*")
corsConfiguration.addAllowedMethod("*")
corsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration) // corsSource 에 corsConfiguration 을 등록한다.
return CorsFilter(corsConfigurationSource)
}
}

View File

@@ -0,0 +1,60 @@
package com.banjjoknim.playground.jwt.config.filter
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* 기본 설정시 Spring Security 는 일련의 Servlet Filter Chain(FilterChainProxy 라는 클래스로 등록되어 있다. 하나의 Filter 로 등록 되어있지만 내부적으로는 여러개의 Filter 가 동작하고 있다) 을 자동으로 구성한다(web tier 에 있는 Spring Security 는 Servlet Filter 에 기반을 두고 있다).
*
* 일반적인 웹 환경에서 브라우저가 서버에게 요청을 보내게 되면, DispatcherServlet(Controller)가 요청을 받기 이전에 많은 ServletFilter(서블릿 필터)를 거치게 된다.
*
* Spring Security 역시 Servlet Filter 로써 작동하며, 인증 또는 권한과 관련한 처리를 진행하게 된다.
*
* 본래 Servlet Filter 는 WAS(Web Application Server)에서 담당하는데 Spring 은 이 Servlet Filter 들을 직접 관리하기 위해서 DelegatingFilterProxy 를 web.xml 에 설정한다.
*
* 이를 통해 Spring 에서 설정된 Servlet Filter Bean 객체를 거치게 된다.
*
* 여기서는 스프링 시큐리티 필터체인에 필터를 추가하는 대신, 직접 필터를 만들어서 사용한다.
*
* 굳이 Security Filter Chain 에 필터를 추가할 필요가 없고, 이렇게 따로 만들어서 사용해도 된다.
*
* Filter 를 Bean 으로 등록해놓으면, 요청이 들어왔을 때 등록된 Filter 가 동작하게 된다.
*
* 이때, Security Filter Chain 이 우리가 직접 만든 Filter 보다 먼저 동작한다.
*
* 만약 우리가 만든 Filter 를 원하는 위치에서 동작하도록 하고 싶다면 원하는 위치에 Filter 를 추가하면 된다.
*
* 이때, Security Filter Chain 의 순서는 com.banjjoknim.playground.config.filter.SecurityFilterChain.png 이미지를 참고하자.
*
* - Filter type의 Bean에는 @Order 어노테이션으로 순서를 정할 수 있다.
* - FilterRegistrationBean을 이용하여 순서를 정할 수 있다
*
* ```kotlin
* http.addFilterBefore(MySecurityFilter3(), SecurityContextPersistenceFilter::class.java)
* ```
*
* @see org.springframework.boot.web.servlet.FilterRegistrationBean
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
* @see org.springframework.web.filter.DelegatingFilterProxy
* @see org.springframework.security.web.FilterChainProxy
*/
@Configuration
class CustomFilterConfiguration {
@Bean
fun customFilter1(): FilterRegistrationBean<CustomFilter1> {
val bean = FilterRegistrationBean(CustomFilter1())
bean.addUrlPatterns("/*") // 모든 요청에 대해 필터가 동작하도록 설정한다.
bean.order = 0 // 필터의 순서를 정할 수 있는데, 낮은 번호가 필터중에서 가장 먼저 실행된다.
return bean
}
@Bean
fun customFilter2(): FilterRegistrationBean<CustomFilter2> {
val bean = FilterRegistrationBean(CustomFilter2())
bean.addUrlPatterns("/*") // 모든 요청에 대해 필터가 동작하도록 설정한다.
bean.order = 1 // 필터의 순서를 정할 수 있는데, 낮은 번호가 필터중에서 가장 먼저 실행된다.
return bean
}
}

View File

@@ -0,0 +1,58 @@
package com.banjjoknim.playground.jwt.config.filter
import org.springframework.http.HttpMethod
import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @see javax.servlet.Filter
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
*/
class CustomFilter1 : Filter {
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
println("필터1")
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
}
}
class CustomFilter2 : Filter {
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
println("필터2")
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
}
}
class CustomFilter3 : Filter {
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
println("필터3")
chain.doFilter(request, response) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
}
}
class CustomAuthorizationFilter : Filter {
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
val httpServletRequest = request as HttpServletRequest
val httpServletResponse = response as HttpServletResponse
if (httpServletRequest.method == HttpMethod.POST.name) {
println("POST 요청됨")
val headerAuthorization = httpServletRequest.getHeader("Authorization")
println(headerAuthorization)
// banjjoknim 이 정상적인 토큰이라고 가정한다.
// 따라서 banjjoknim 이라는 토큰을 id, password 가 정상적으로 입력되었을 때 토큰을 만들어주고 응답에 실어보낸다.
// 클라이언트는 요청할 때마다 해당 토큰을 Header 중 Authorization 의 값으로 포함하여 요청한다.
// 따라서 클라이언트가 요청할 때 Authorization 의 값으로 포함되어 온 토큰이 우리 서버에서 만든 토큰이 맞는지 검증만 하면 된다(RSA, HS256).
if (headerAuthorization == "banjjoknim") {
chain.doFilter(httpServletRequest, httpServletResponse) // request, response 와 함께 doFilter 를 호출해주어야 한다. 그렇지 않으면 현재 필터가 진행되고나서 이 이후의 필터들은 더이상 동작하지 않게 된다.
} else {
val printWriter = httpServletResponse.writer
printWriter.println("인증안됨") // 응답에 '인증안됨' 을 쓴다.
}
}
}
}

View File

@@ -0,0 +1,153 @@
package com.banjjoknim.playground.jwt.config.filter
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.banjjoknim.playground.jwt.config.security.JwtSecurityProperties
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
import com.banjjoknim.playground.jwt.domain.user.JwtUser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.springframework.http.HttpHeaders
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import java.util.Date
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Spring Security 에는 UsernamePasswordAuthenticationFilter 가 있다.
*
* 기본적으로는 /login 요청에서 username, password 를 전송하면 (post 요청) UsernamePasswordAuthenticationFilter 가 동작한다.
*
* 하지만 우리는 formLogin().disable() 설정을 해주었기 때문에 직접 Filter 를 만들어서 Security 설정에 등록해주어야 한다. 그래야 Security 에서 UserDetailsService 를 호출할 수 있다.
*
* 단, Security 에 등록해줄 때 AuthenticationManager 와 함께 등록해주어야 한다. AuthenticationManager 를 통해서 로그인이 진행되기 때문이다.
*
* 참고로, AuthenticationManager 는 WebSecurityConfigurerAdapter 가 들고 있고, 그 녀석을 사용하면 된다.
*
* AuthenticationManager 는 AbstractAuthenticationProcessingFilter 또한 가지고 있으므로
* UsernamePasswordAuthenticationFilter 를 상속받아서 사용하는 대신 AbstractAuthenticationProcessingFilter 를 상속받아서 사용해도 된다.
*
* @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
* @see org.springframework.security.authentication.AuthenticationManager
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
* @see com.banjjoknim.playground.jwt.config.security.JwtSecurityConfiguration
*/
class JwtAuthenticationFilter(
private val authenticationManagerFromSecurityConfiguration: AuthenticationManager // authenticationManager 로 변수명을 지으면 이름이 겹쳐서 컴파일 에러가 발생하여 변수명 변경.
) : UsernamePasswordAuthenticationFilter() {
/**
* 기존의 /login URL로 요청을 하면 로그인 시도를 위해 호출되는 함수이다.
*
* 추상 메서드로, AbstractAuthenticationProcessingFilter 에 포함되어 있으며,
* AbstractAuthenticationProcessingFilter 를 상속받은 UsernamePasswordAuthenticationFilter, OAuth2LoginAuthenticationFilter 등이 구현하고 있다.
*
* AbstractAuthenticationProcessingFilter#doFilter(HttpServletRequest, HttpServletResponse) 에서 내부적으로 호출하고 있다.
*
* /login URL로 요청을 하면 UsernamePasswordAuthenticationFilter 가 해당 요청을 낚아채서 아래의 함수가 자동으로 실행된다.
*
* 따라서 구현해줘야 하는 것들은 아래와 같다.
*
* 1. username & password 를 받는다.
* 2. 포함하고 있는 AuthenticationManager로 정상인지 로그인 시도를 한다.
* 3. 로그인 시도를 하면 우리가 만든 PrincipalDetailsService#loadUserByUsername(String) 이 호출된다.
* - 데이터베이스로부터 일치하는 id, password 가 있는지 검사한다.
* - 로직이 정상적으로 완료되면 로그인을 시도한 유저의 정보를 담고 있는 Authentication 객체가 반환된다.
* 4. 정상적으로 로직이 수행되어서 Authentication 객체가 리턴되면 해당 객체를 리턴해서 Spring Security 세션에 담는다.
* - 만약 세션에 Authentication 객체를 담지 않으면 Spring Security 에서의 권한관리가 동작하지 않는다.
* - Spring Security 는 세션에 Authentication 객체가 존재해야 권한관리를 해준다.
* - 만약 Spring Security 를 통해 권한관리를 안할거면 Authentication 객체를 세션에 담을 필요가 없다.
* 5. 마지막으로 JWT 토큰을 만들어서 응답으로 돌려주면 된다(선택-successfulAuthentication() 을 override 해서 구현해줘도 됨).
*
* @see org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
* @see org.springframework.security.authentication.AuthenticationManager
* @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
* @see org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter
* @see com.banjjoknim.playground.jwt.config.security.PrincipalDetailsService
* @see org.springframework.security.authentication.UsernamePasswordAuthenticationToken
*/
override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
println("JwtAuthenticationFilter : 로그인 시도중")
// println(request.inputStream) // username, password 가 담겨있다. request의 inputStream 은 Request 당 1회만 호출할 수 있으므로 주석처리.
// val bufferedReader = request.reader
// bufferedReader.lineSequence().forEach(::println) // request 데이터 확인
val objectMapper = ObjectMapper().registerKotlinModule()
val jwtUser = objectMapper.readValue(request.inputStream, JwtUser::class.java)
// println(jwtUser)
// 로그인 시도를 위해서 id, password 를 이용해서 직접 토큰을 만든다.
// UsernamePasswordAuthenticationFilter#attemptAuthentication() 함수를 참고하도록 한다.
// 즉, 우리가 직접 토큰을 만들어서 호출을 대신 수행해준다고 보면 될듯.
val authenticationToken = UsernamePasswordAuthenticationToken(jwtUser.username, jwtUser.password)
// 직접 만든 토큰을 인자로 넣고 AuthenticationManager#authenticate(Token) 을 호출하면
// 내부적으로 로직이 돌면서 우리가 만든 PrincipalDetailsService#loadUserByUsername(String) 함수가 호출된다.
// 그 결과로 User의 로그인 정보가 담긴 Authentication 객체를 얻을 수 있다.
// Authentication 객체를 얻어다는 것은 데이터베이스에 있는 username 과 password 가 일치한다는 뜻이다.
val authentication = authenticationManagerFromSecurityConfiguration.authenticate(authenticationToken)
// 위 처럼 인증이 정상적으로 진행되어 Authentication 객체를 얻었다면
// 아래처럼 Authentication 객체 내부의 PrincipalDetails 객체를 꺼내어 정보 확인이 가능하다.
// 즉, 로그인이 정상적으로 되었다는 뜻이다.
val principalDetails = authentication.principal as PrincipalDetails
println("로그인 완료됨: ${principalDetails.user.username}")
// return super.attemptAuthentication(request, response)
// 로그인이 정상적으로 되었으므로 Authentication 객체를 Session 영역에 저장해야 한다.
// Authentication 객체를 Session 영역에 저장하는 방법은 Authentication 객체를 return 해주는 것이다.
// Authentication 객체를 return 해주면 Spring Security 가 자동으로 Authentication 객체를 Security Session 영역에 저장해준다.
// Authentication 객체를 return 해서 Session 영역에 저장하는 이유는 권한 관리를 Spring Security 가 대신 해주어 관리가 편해지기 때문이다(원하지 않으면 Session 영역에 저장을 안하면 된다).
// JWT 토큰을 사용한다면 Session 영역을 굳이 만들 필요가 없다. 다만, 권한 처리 때문에 Session 에 저장하는 것이다.
// 기본적으로 Authentication 객체를 세션에 저장하는 로직은 AbstractAuthenticationProcessingFilter#successfulAuthentication() 함수에서 수행하고 있다.
// Security Session 영역에 저장되는 정보들은 잠시 사용하고 응답이 끝났을 때 버리면 된다(세션 정보는 시간이 지나면 자동으로 사라진다).
return authentication
}
/**
* 본 함수는 attemptAuthentication() 함수를 통한 인증이 성공적으로 이루어져서 Authentication 객체를 얻을 수 있는 경우 그 다음으로 호출되는 함수다.
*
* AbstractAuthenticationProcessingFilter#successfulAuthentication() 함수에는 Security Session 영역에 Authentication 객체를 저장하는 로직이 포함되어 있다.
*
* 자세한 내용은 AbstractAuthenticationProcessingFilter#successfulAuthentication() 에 달린 javadoc 을 참고하도록 하자.
*
* 따라서, 여기서 JWT 토큰을 만들어서 Request 요청한 사용자에게 JWT 토큰을 응답해주면 된다(선택사항).
*
* 기존의 username, password 방식의 로그인을 사용할 경우, 스프링 시큐리티는 세션이 유효할 경우 인증이 필요한 페이지의 권한을 체크해서 알아서 인증이 필요한 페이지로 이동시켜준다.
*
* 기존의 서버는 세션의 유효성 검증을 할 때 Session.getAttribute("세션값 확인") 와 같은 방식으로 확인하기만 하면 된다.
*
* 하지만 토큰 방식을 사용하게되면, 세션ID도 만들지 않고, 쿠키도 응답에 제공해주지 않는다(세션에 데이터를 담아둘게 아니다).
*
* 대신, JWT 토큰을 생성하고 클라이언트쪽으로 JWT 토큰을 응답해준다. 따라서 요청할 때마다 JWT 토큰을 가지고 요청해야 한다.
*
* 따라서 서버는 JWT 토큰이 유효한지를 판단해야하는데, 이 부분에 대한 필터를 따로 만들어주어야 한다.
*/
override fun successfulAuthentication(
request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain,
authResult: Authentication
) {
val principalDetails = authResult.principal as PrincipalDetails
println("successfulAuthentication 실행됨 : ${principalDetails.user.username}의 인증이 완료되었다는 뜻.")
// RSA 방식은 아니다. Hash 암호 방식.
val jwtToken = JWT.create()
.withSubject("banjjoknim 토큰")
.withExpiresAt(Date(System.currentTimeMillis() + JwtSecurityProperties.EXPIRATION_TIME_SECONDS))
.withClaim("id", principalDetails.user.id)
.withClaim("username", principalDetails.user.username)
.sign(Algorithm.HMAC512(JwtSecurityProperties.SECRET)) // 서버에서만 알고 있는 비밀 키를 사용한다.
response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer $jwtToken")
super.successfulAuthentication(request, response, chain, authResult)
}
}

View File

@@ -0,0 +1,80 @@
package com.banjjoknim.playground.jwt.config.filter
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.banjjoknim.playground.jwt.config.security.JwtSecurityProperties
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
import com.banjjoknim.playground.jwt.domain.user.JwtUserRepository
import org.springframework.http.HttpHeaders
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* 로그인을 통해 발행된 JWT 토큰의 전자서명을 이용해서 개인정보에 접근할 수 있게 하기 위한 커스텀 필터.
*
* Security 가 가진 Filter 중에서 BasicAuthenticationFilter 라는 것이 있다.
*
* 권한이나 인증이 필요한 특정 URL 을 요청했을 때 위 BasicAuthenticationFilter 를 무조건 거치게 되어 있다.
*
* 만약 권한이나 인증이 필요한 주소가 아니라면 위 필터를 거치지 않는다. 따라서 BasicAuthenticationFilter 를 상속받아서 필요한 로직을 구현해준다.
*
* @see org.springframework.security.web.authentication.www.BasicAuthenticationFilter
*/
class JwtAuthorizationFilter(
private val authenticationManagerFromSecurityConfiguration: AuthenticationManager,
private val jwtUserRepository: JwtUserRepository
) :
BasicAuthenticationFilter(authenticationManagerFromSecurityConfiguration) {
/**
* 인증이나 권한이 필요한 URL 요청이 있을 때 BasicAuthenticationFilter#doFilterInternal() 함수를 거치게 된다.
*
* 따라서 이 함수에서 Header 의 JWT 토큰에 대한 처리를 진행해주면 된다.
*/
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
println("인증이나 권한이 필요한 주소가 요청됨.")
val jwtHeader = request.getHeader(HttpHeaders.AUTHORIZATION)
println("jwtHeader: $jwtHeader")
// Header의 JWT 토큰이 정상적인지 검사한다.
if (jwtHeader == null || !jwtHeader.startsWith("Bearer")) {
chain.doFilter(request, response)
return
}
// JWT 토큰을 검증해서 정상적인 사용자인지 검사한다.
val jwtToken = jwtHeader.replace(JwtSecurityProperties.BEARER_TOKEN_PREFIX, "")
val jwtVerifier = JWT.require(Algorithm.HMAC512(JwtSecurityProperties.SECRET)).build()
val username = jwtVerifier.verify(jwtToken).getClaim("username").asString()
// username 이 null 이 아니라면 서명이 정상적으로 된 것이다.
if (username != null) {
println("username 정상. username: $username")
val jwtUser = jwtUserRepository.findByUsername(username)
?: throw IllegalArgumentException("can not found jwtUser. username: $username")
val principalDetails = PrincipalDetails(jwtUser)
// Authentication 객체를 강제로 만든다. password 의 경우는 null 을 사용해도 무방하다. 우리가 직접 Authentication 객체를 만들기 때문이다.
// 이게 가능한 이유는, username 이 null 이 아니기 때문인데, username 이 null 이 아니라는 것은 인증이 정상적으로 진행되었다는 뜻이기 때문.
// 단, 이렇게 Authentication 객체를 만들 때는 권한을 직접 알려주어야(지정해주어야) 한다.
// 즉, JWT 토큰 서명을 통해서 서명이 정상이면 Authentication 객체를 만들어준다.
val authenticationToken =
UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.authorities)
// SecurityContext 는 Security 의 세션 공간이다.
val securityContext = SecurityContextHolder.getContext()
// 강제로 Security 의 세션에 접근하여 Authentication 객체를 저장한다. 만약 세션에 저장이 제대로 되면 Authentication 객체를 Controller 단에서 가져올 수 있다.
securityContext.authentication = authenticationToken
}
// super.doFilterInternal(request, response, chain) // 아래의 chain.doFilter(request, response) 에서도 응답을 하기 때문에 응답을 총 2번하게 되어 오류가 나므로 지워줘야 한다.
chain.doFilter(request, response)
}
}

View File

@@ -0,0 +1,128 @@
package com.banjjoknim.playground.jwt.config.security
import com.banjjoknim.playground.jwt.config.filter.CustomAuthorizationFilter
import com.banjjoknim.playground.jwt.config.filter.CustomFilter3
import com.banjjoknim.playground.jwt.config.filter.JwtAuthenticationFilter
import com.banjjoknim.playground.jwt.config.filter.JwtAuthorizationFilter
import com.banjjoknim.playground.jwt.domain.user.JwtUser
import com.banjjoknim.playground.jwt.domain.user.JwtUserRepository
import org.springframework.context.annotation.Bean
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.context.SecurityContextPersistenceFilter
import org.springframework.stereotype.Service
import org.springframework.web.filter.CorsFilter
/**
* SessionCreationPolicy 설정을 STATELESS 로 사용하면 세션을 만드는 방식을 사용하지 않게 된다.
*
* 토큰 기반(JWT)을 사용한 설정에서는 기본이며, 상태가 없는 서버를 만들 때 사용한다.
*
* ```kotlin
* Spring Filter Chain 에 존재하는 BasicAuthenticationFilter의 동작 이전에 MySecurityFilter1 을 추가한다. 하지만 반드시 SecurityFilter 에 Filter 를 추가할 필요는 없다.
*
* http.addFilterBefore(MySecurityFilter1(), BasicAuthenticationFilter::class.java)
* ```
* @see org.springframework.security.config.http.SessionCreationPolicy
*/
@EnableWebSecurity // 시큐리티 활성화 -> 시큐리티 설정을 기본 스프링 필터체인에 등록한다.
class JwtSecurityConfiguration(
private val corsFilter: CorsFilter, // CorsConfiguration 에서 Bean 으로 등록해준 CorsFilter 를 Spring 으로부터 DI 받는다.
private val jwtUserRepository: JwtUserRepository
) : WebSecurityConfigurerAdapter() {
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
override fun configure(http: HttpSecurity) {
// Spring Filter Chain 에 존재하는 BasicAuthenticationFilter의 동작 이전에 MySecurityFilter1 을 추가한다. 하지만 반드시 SecurityFilter 에 Filter 를 추가할 필요는 없다.
// http.addFilterBefore(MySecurityFilter1(), BasicAuthenticationFilter::class.java)
// 우리가 원하는 위치에 Filter 를 등록한다. 만약 Spring Security Filter 보다도 먼저 실행되게 하고 싶다면 SecurityContextPersistenceFilter 보다 먼저 실행되도록 아래처럼 등록해주면 된다.
http.addFilterBefore(CustomFilter3(), SecurityContextPersistenceFilter::class.java)
http.addFilterBefore(CustomAuthorizationFilter(), SecurityContextPersistenceFilter::class.java)
http.csrf().disable()
// 기본적으로 웹은 STATELESS 인데, STATEFUL 처럼 쓰기 위해서 세션과 쿠키를 만든다. 이때, 그걸(세션과 쿠키) 사용하지 않도록 설정하는 것이다.
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션을 사용하지 않겠다는 설정. 토큰 기반에서는 기본 설정이다. 상태가 없는 서버를 만든다.
.and()
.addFilter(corsFilter) // filter 에 Bean 으로 등록해준 CorsFilter 를 추가한다. 따라서 모든 요청은 추가된 CorsFilter 를 거치게 된다. 이렇게 하면 내 서버는 CORS 정책에서 벗어날 수 있다(Cross-origin 요청이 와도 다 허용될 것이다).
.formLogin().disable() // Form 태그 방식 로그인을 사용하지 않는다.
.httpBasic().disable() // HttpBasic 방식 로그인을 사용하지 않는다.
// formLogin().disable() 로 인해 직접 만든 필터를 등록해주어야 Security 가 UserDetailsService 를 호출할 수 있다.
// 이때, WebSecurityConfigurerAdapter 에 포함되어 있는 AuthenticationManager 라는 녀석과 함께 등록해주어야 한다.
.addFilter(JwtAuthenticationFilter(super.authenticationManager()))
.addFilter(JwtAuthorizationFilter(super.authenticationManager(), jwtUserRepository))
.authorizeRequests()
.antMatchers("/api/v1/user/**").hasAnyRole("USER", "MANAGER", "ADMIN")
.antMatchers("/api/v1/manager/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/api/v1/admin/**").hasAnyRole("ADMIN")
.anyRequest().permitAll()
}
}
class PrincipalDetails(
val user: JwtUser
) : UserDetails {
override fun getAuthorities(): Collection<GrantedAuthority> {
val authorities = mutableListOf<GrantedAuthority>()
for (role in user.getRoles()) {
authorities.add(GrantedAuthority { role })
// authorities + GrantedAuthority { role }
}
return authorities
}
override fun getPassword(): String {
return user.password
}
override fun getUsername(): String {
return user.username
}
override fun isAccountNonExpired(): Boolean {
return true
}
override fun isAccountNonLocked(): Boolean {
return true
}
override fun isCredentialsNonExpired(): Boolean {
return true
}
override fun isEnabled(): Boolean {
return true
}
}
/**
* 원래는 http://localhost:8080/login 요청이 올 때 동작한다(Spring Security 의 기본 로그인 url).
*
* 하지만 우리는 formLogin().disable() 했기 때문에 위 url로 요청이 들어올 때 직접 PrincipalDetailsService 를 호출할 Filter 를 만들어줘야 한다.
*/
@Service
class PrincipalDetailsService(
private val jwtUserRepository: JwtUserRepository
) : UserDetailsService {
override fun loadUserByUsername(username: String): UserDetails {
val jwtUser = jwtUserRepository.findByUsername(username)
?: throw UsernameNotFoundException("can not found user by username. username: $username")
return PrincipalDetails(jwtUser)
}
}

View File

@@ -0,0 +1,7 @@
package com.banjjoknim.playground.jwt.config.security
object JwtSecurityProperties {
const val SECRET = "banjjoknim"
const val EXPIRATION_TIME_SECONDS = 60 * 1000 * 10 // 10분 (1/1000 초를 기준으로 한다)
const val BEARER_TOKEN_PREFIX = "Bearer "
}

View File

@@ -0,0 +1,27 @@
package com.banjjoknim.playground.jwt.domain.home
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
/**
* `@CrossOrigin` 어노테이션을 사용하더라도 Security 인증이 필요한 요청은 전부 거부된다.
*
* `@CrossOrigin` 어노테이션은 인증이 필요하지 않은 요청만 허용해준다.
*
* @see org.springframework.web.bind.annotation.CrossOrigin
*/
//@CrossOrigin("*")
@RestController
class HomeApiController {
@GetMapping("/home")
fun home(): String {
return "<h1>home</h1>"
}
@PostMapping("/token")
fun token(): String {
return "<h1>token</h1>"
}
}

View File

@@ -0,0 +1,23 @@
package com.banjjoknim.playground.jwt.domain.user
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
@Entity
class JwtUser(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0L,
var username: String = "",
var password: String = "",
var roles: String = "" // USER, ADMIN
) {
fun getRoles(): List<String> {
if (roles.isNotEmpty()) {
return roles.split(",")
}
return emptyList()
}
}

View File

@@ -0,0 +1,45 @@
package com.banjjoknim.playground.jwt.domain.user
import com.banjjoknim.playground.jwt.config.security.PrincipalDetails
import org.springframework.security.core.Authentication
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
@RestController
class JwtUserController(
private val jwtUserRepository: JwtUserRepository,
private val passwordEncoder: PasswordEncoder
) {
@PostMapping("/join")
fun join(@RequestBody jwtUser: JwtUser): String {
jwtUser.password = passwordEncoder.encode(jwtUser.password)
jwtUser.roles = "ROLE_USER"
jwtUserRepository.save(jwtUser)
return "회원가입완료"
}
// user 권한만 접근 가능
@GetMapping("/api/v1/user")
fun user(@AuthenticationPrincipal authentication: Authentication): String {
val principalDetails = authentication.principal as PrincipalDetails
println("Authentication: ${principalDetails.username}")
return "user"
}
// manager, admin 권한만 접근 가능
@GetMapping("/api/v1/manager")
fun manager(): String {
return "manager"
}
// admin 권한만 접근 가능
@GetMapping("/api/v1/admin")
fun admin(): String {
return "admin"
}
}

View File

@@ -0,0 +1,7 @@
package com.banjjoknim.playground.jwt.domain.user
import org.springframework.data.jpa.repository.JpaRepository
interface JwtUserRepository : JpaRepository<JwtUser, Long> {
fun findByUsername(username: String): JwtUser?
}

View File

@@ -1,4 +1,17 @@
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/security?serverTimezone=Asia/Seoul
username: root
password: password!
jpa:
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
security:
oauth2:
client: