티스토리 뷰

 

이어서 계속 구현해보겠습니다.

 

구현 자체가 목적이므로 자세한 설명을 생략합니다.

 

  1. JWT 생성하기
  2. JWT에 권한 추가해주기 
  3. 생성한 JWT에 대해 인증/인가 하기 
  4. JWT 재발급 해주기 (진행)

구현

AuthController

@RestController
@RequestMapping("/auth")
class AuthController(
    private val authService: AuthService
) {

    /**
     * token 생성해서 보내주기
     */
    @GetMapping("/login")
    fun login(@AuthenticationPrincipal oAuth2User: OAuth2User): ResponseEntity<JwtDto> {
        return ResponseEntity.ok(authService.login(oAuth2User))
    }

    @PostMapping("/reissue")
    fun reissue(@RequestBody reissueRequestDto: ReissueRequestDto): ResponseEntity<JwtDto> {
        return ResponseEntity.ok(authService.reissue(reissueRequestDto))
    }
}

 

AuthService

@Service
class AuthService(
    private val memberRepository: MemberRepository,
    private val jwtProvider: JwtProvider
) {

    @Transactional
    fun login(oAuth2User: OAuth2User) : JwtDto {
        //TODO: 1. 회원이 아니라면 회원 가입을 시켜준다.
        if(!memberRepository.existsByEmail(oAuth2User.attributes["email"] as String)) {
            val member = Member(
                email = oAuth2User.attributes["email"] as String,
                role = AuthType.ROLE_USER
            )
            memberRepository.save(member)
        }

        //TODO: 2. token 을 생성해준다.
        return jwtProvider.generateJwtDto(oAuth2User.attributes["email"] as String)
    }

    @Transactional(readOnly = true)
    fun reissue(reissueRequestDto: ReissueRequestDto): JwtDto {
        jwtProvider.validateRefreshToken(reissueRequestDto.refreshToken)

        val authentication = jwtProvider.findAuthentication(reissueRequestDto.refreshToken)

        return jwtProvider.generateJwtDto(authentication.name)
    }
}

 

JwtProvider

@Component
class JwtProvider(
    private val memberRepository: MemberRepository
) {

    companion object {
        private const val AUTHORITIES_KEY = "auth"
        private const val BEARER_TYPE = "bearer"
        private const val ACCESS_TOKEN_EXPIRE_TIME = (1000 * 60 * 30)
        private const val REFRESH_TOKEN_EXPIRE_TIME = (1000 * 60 * 60 * 24 * 7)
    }

    private val key: Key by lazy {
        val secretKey: String = "ZVc3Z0g4bm5TVzRQUDJxUXBIOGRBUGtjRVg2WDl0dzVYVkMyWWs1Qlk3NkZBOXh1UzNoRWUzeTd6cVdEa0x2eQo=" // base64Encoded
        Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey))
    }

    fun generateJwtDto(email: String) : JwtDto {
        val now = Date().time
        val accessTokenExpiresIn: Date = Date(now + ACCESS_TOKEN_EXPIRE_TIME)

        val member = memberRepository.findByEmail(email)

        val accessToken = Jwts.builder()
            .setSubject(member?.email) // payload "sub": "email"
            .claim(AUTHORITIES_KEY, member?.role)  // payload "auth": "ROLE_USER"
            .setExpiration(accessTokenExpiresIn) // payload "exp": 1516239022 (예시)
            .signWith(key, SignatureAlgorithm.HS512) // header "alg": "HS512"
            .compact()

        val refreshToken = Jwts.builder()
            .setSubject(member?.email)
            .claim(AUTHORITIES_KEY, member?.role)
            .setExpiration(Date(now + REFRESH_TOKEN_EXPIRE_TIME))
            .signWith(key, SignatureAlgorithm.HS512)
            .compact()

        return JwtDto(
            grantType = BEARER_TYPE,
            accessToken = accessToken,
            refreshToken = refreshToken,
            accessTokenExpiresIn = accessTokenExpiresIn.time
        )
    }

    fun resolveToken(request: HttpServletRequest): String {
        val bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION)

        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(AccessTokenType.BEARER.value)) {
            return bearerToken.substring(7)
        }

        return ""
    }

    fun validateAccessToken(token: String): Boolean {
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token)
            return true
        } catch (e: SecurityException) {
            println("올바르지 못한 토큰입니다.")
        } catch (e: MalformedJwtException) {
            println("올바르지 못한 토큰입니다.")
        } catch (e: ExpiredJwtException) {
            println("만료된 토큰입니다.")
        } catch (e: UnsupportedJwtException) {
            println("지원되지 않는 토큰입니다.")
        } catch (e: IllegalArgumentException) {
            println("잘못된 토큰입니다.")
        }
        return true
    }

    fun validateRefreshToken(token: String) {
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token)
        } catch (e: SecurityException) {
            println("올바르지 못한 토큰입니다.")
        } catch (e: MalformedJwtException) {
            println("올바르지 못한 토큰입니다.")
        } catch (e: ExpiredJwtException) {
            println("만료된 토큰입니다.")
        } catch (e: UnsupportedJwtException) {
            println("지원되지 않는 토큰입니다.")
        } catch (e: IllegalArgumentException) {
            println("잘못된 토큰입니다.")
        }
    }

    fun findAuthentication(accessToken: String): Authentication {
        val claims = parseClaims(accessToken)

        val authorities = mutableListOf(claims[AUTHORITIES_KEY] as String).map { role -> SimpleGrantedAuthority(role) }
        val user = User(claims[Claims.SUBJECT] as String, "", authorities)

        return UsernamePasswordAuthenticationToken(user, "", authorities)
    }

    private fun parseClaims(accessToken: String): Claims {
        return try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(accessToken).body
        } catch (e: ExpiredJwtException) {
            e.claims
        }
    }
}

 

ReissueRequestDto

data class ReissueRequestDto(
    val refreshToken: String
) {
}

 

SecurityConfig

@Configuration
class SecurityConfig(
    private val customUserDetailService: CustomUserDetailService,
    private val jwtProvider: JwtProvider
) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
            .csrf {
                it.disable()
            }
            .httpBasic {
                it.disable()
            }
            .sessionManagement {
                it.sessionCreationPolicy(SessionCreationPolicy.NEVER)
            }
            .authorizeRequests {
                it.antMatchers("/auth/reissue").permitAll()
                it.antMatchers("/guest").hasRole("USER")
                it.antMatchers("/admin").hasRole("ADMIN")
            }
            .oauth2Login {
                it.userInfoEndpoint().userService(customUserDetailService)
                it.defaultSuccessUrl("/auth/login")
                it.failureUrl("/fail")
            }
            .addFilterBefore(JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter::class.java)
    }
}

 


실행

 

1. POST /auth/reissue로 접근합니다. body에는 refreshToken이 담깁니다.

 

이렇게 Spring Security를 이용해서 Oauth2, JWT를 구현해보았습니다.

 

코드는 Best Practice는 아니며 예외처리, 스트링 안티 패턴 등을 활용하여서 추가 개발하시길 바랍니다.

 

전체 코드는 깃헙에서 확인하실 수 있습니다.

 

댓글
댓글쓰기 폼
공지사항
Total
208,300
Today
615
Yesterday
833
링크
«   2022/08   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
글 보관함