์ด์ด์ ๊ณ์ ๊ตฌํํด๋ณด๊ฒ ์ต๋๋ค.
๊ตฌํ ์์ฒด๊ฐ ๋ชฉ์ ์ด๋ฏ๋ก ์์ธํ ์ค๋ช ์ ์๋ตํฉ๋๋ค.
- JWT ์์ฑํ๊ธฐ
- JWT์ ๊ถํ ์ถ๊ฐํด์ฃผ๊ธฐ (์งํ)
- ์์ฑํ JWT์ ๋ํด ์ธ์ฆ/์ธ๊ฐ ํ๊ธฐ
- JWT ์ฌ๋ฐ๊ธ ํด์ฃผ๊ธฐ
๊ตฌํ
@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(oAuth2User: OAuth2User) : JwtDto {
val now = Date().time
val accessTokenExpiresIn: Date = Date(now + ACCESS_TOKEN_EXPIRE_TIME)
val member = memberRepository.findByEmail(oAuth2User.attributes["email"] as String)
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)
.setExpiration(Date(now + REFRESH_TOKEN_EXPIRE_TIME))
.signWith(key, SignatureAlgorithm.HS512)
.compact()
return JwtDto(
grantType = BEARER_TYPE,
accessToken = accessToken,
refreshToken = refreshToken,
accessTokenExpiresIn = accessTokenExpiresIn.time
)
}
}
JWT ์ payload ๋ถ๋ถ์ auth ๋ง ์ถ๊ฐํด์ฃผ์์ต๋๋ค.
๊ถํ์ DB์ ์ ์ฅํ ํ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์์ ๋ด๊ฒ ๋ฉ๋๋ค.
์คํ
1. http://localhost:8080/oauth2/authorization/google ๋ก ์ ์ ํ, ๊ณ์ ์ ์ ํํฉ๋๋ค.
2. JWT๋ฅผ ๋ถ์ฌ๋ฐ์ต๋๋ค.
3. https://jwt.io/ ์์ ํ์ธํด๋ด ๋๋ค.
payload ๋ถ๋ถ์ auth๊ฐ ์ถ๊ฐ๋ ๊ฒ์ ๋ณผ ์ ์์ต๋๋ค.
- JWT ์์ฑํ๊ธฐ
- JWT์ ๊ถํ ์ถ๊ฐํด์ฃผ๊ธฐ (์๋ฃ)
- ์์ฑํ JWT์ ๋ํด ์ธ์ฆ/์ธ๊ฐ ํ๊ธฐ
- JWT ์ฌ๋ฐ๊ธ ํด์ฃผ๊ธฐ