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

 

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

 

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

 

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

๊ตฌํ˜„

 

JwtFilter

class JwtFilter(
    private val jwtProvider: JwtProvider
) : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        val jwt = jwtProvider.resolveToken(request)

        if (StringUtils.hasText(jwt) && jwtProvider.validateAccessToken(jwt)) {
            val authentication = jwtProvider.findAuthentication(jwt)
            SecurityContextHolder.getContext().authentication = authentication
        }

        filterChain.doFilter(request, response)
    }
}

 

JWT ๊ฒ€์ฆ์€ Filter๋ฅผ ํ†ตํ•ด์„œ ์ง„ํ–‰๋ฉ๋‹ˆ๋‹ค.

 

resolveToken์€ header์—์„œ bearer๋ฅผ ์ œ์™ธํ•œ ์ˆœ์ˆ˜ ํ† ํฐ๋งŒ์„ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค.

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(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
        )
    }

    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 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
        }
    }
}

 

resolveToken, validateAccessToken, findAuthentication, parseClaims ํ•จ์ˆ˜๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

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("/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)
    }
}

/guest ์™€ /admin์„ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

 

MainController

@RestController
class MainController {


    @GetMapping("/success")
    fun success(): String {
        return "success"
    }

    @GetMapping("/fail")
    fun fail(): String {
        return "fail"
    }

    @GetMapping("/guest")
    fun guest(): String {
        return "guest"
    }

    @GetMapping("/admin")
    fun admin(): String {
        return "admin"
    }
}

 


์‹คํ–‰

1. ๊ตฌ๊ธ€ ๊ณ„์ •์œผ๋กœ ๋กœ๊ทธ์ธ์„ ํ•œ ํ›„, jwt์„ ๋ฐœ๊ธ‰ ๋ฐ›์Šต๋‹ˆ๋‹ค.

 

2. ๋ฐœ๊ธ‰ ๋ฐ›์€ ํ† ํฐ์€ User๋กœ /guest๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

3. ์ด๋ฒˆ์—” Admin์ด ์ ‘๊ทผ ๊ฐ€๋Šฅํ•œ /admin๋กœ ์ ‘๊ทผ์„ ์‹œ๋„ํ•ด๋ด…๋‹ˆ๋‹ค.

 

4. Forbidden์ด ๋œจ๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๊ณ , ์ ‘๊ทผ์„ ํ•˜๊ณ  ์‹ถ์œผ๋ฉด DB์— ์ €์žฅ๋œ ROLE_USER๋ฅผ ROLE_ADMIN์œผ๋กœ ๋ฐ”๊พธ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

profile on loading

Loading...