Refresh Token Redis로 저장하기

2024. 7. 30. 21:14TIL

 

오늘의 진행상황

 

로그인, 로그아웃 기능에 Refresh Token을 Redis에 저장하고 삭제하는 로직 추가

override fun login(request: LoginRequest): TokenResponse {
    val loginMember = memberRepository.findByEmail(request.email)
        ?: throw IllegalStateException("이메일이 없음")
    check(passwordEncoder.matches(request.password, loginMember.password)) { "비밀번호가 맞지 않음" }

    val tokens = jwtTokenManager.generateToken(loginMember.id!!, MemberRole.MEMBER)

    redisTemplate.opsForValue().set("refreshToken::${loginMember.id}", tokens.refreshToken, 7, TimeUnit.DAYS) //7일!!
    return tokens
}

override fun logout(request: RefreshTokenRequest) {
    jwtTokenManager.validateToken(request.refreshToken).map {
        redisTemplate.delete("refreshToken::${it.payload.subject.toLong()}")
    }
}

 

accessToken이 만료되어 RefreshToken을 통해 accessToken을 재발급 받을때 refreshToken을 새로 발급하는 로직 추가


@Service
class RefreshTokenService(
    private val jwtTokenManager: JwtTokenManager,
    private val redisTemplate: RedisTemplate<String, String>
) {

    fun refreshAccessToken(request: RefreshTokenRequest): TokenResponse {
        val refreshToken = request.refreshToken

        return jwtTokenManager.validateToken(refreshToken).fold(
            onSuccess = {
                val tokens = jwtTokenManager.generateToken(
                    memberId = it.payload.subject.toLong(),
                    memberRole = MemberRole.valueOf(it.payload.get("memberRole", String::class.java))
                )
                redisTemplate.delete("refreshToken::${it.payload.subject.toLong()}")
                redisTemplate.opsForValue()
                    .set("refreshToken::${it.payload.subject.toLong()}", tokens.refreshToken, 7, TimeUnit.DAYS)
                tokens
            },
            onFailure = { throw IllegalStateException(" 토큰이 검증되지않음") }
        )
    }
}

 

 

Refresh Token을 서버측에 저장하기 위한 방법으로 Redis를 활용