๋กœ์ผ“๐Ÿพ
article thumbnail

 

์ด์–ด์„œ ๊ณ„์† ๊ตฌํ˜„ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๊ตฌํ˜„ ์ž์ฒด๊ฐ€ ๋ชฉ์ ์ด๋ฏ€๋กœ ์ž์„ธํ•œ ์„ค๋ช…์„ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

 

  1. JWT ์ƒ์„ฑํ•˜๊ธฐ
  2. JWT์— ๊ถŒํ•œ ์ถ”๊ฐ€ํ•ด์ฃผ๊ธฐ (์ง„ํ–‰)
  3. ์ƒ์„ฑํ•œ JWT์— ๋Œ€ํ•ด ์ธ์ฆ/์ธ๊ฐ€ ํ•˜๊ธฐ
  4. 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๊ฐ€ ์ถ”๊ฐ€๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

  1. JWT ์ƒ์„ฑํ•˜๊ธฐ
  2. JWT์— ๊ถŒํ•œ ์ถ”๊ฐ€ํ•ด์ฃผ๊ธฐ (์™„๋ฃŒ)
  3. ์ƒ์„ฑํ•œ JWT์— ๋Œ€ํ•ด ์ธ์ฆ/์ธ๊ฐ€ ํ•˜๊ธฐ
  4. JWT ์žฌ๋ฐœ๊ธ‰ ํ•ด์ฃผ๊ธฐ
profile on loading

Loading...