인증이 안되는 현상이 벌어저서
data class UserPrincipal(
val id: Long,
val email: String,
)
@Component
class JwtAuthenticationFilter(
private val jwtPlugin: JwtPlugin
) : OncePerRequestFilter() {
@Throws(IOException::class, ServletException::class)
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
chain: FilterChain
) {
val header = request.getHeader("Authorization")
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response)
return
}
val token = header.replace("Bearer ", "")
val result = jwtPlugin.validateToken(token)
if (result.isSuccess) {
val claims: Jws<Claims> = result.getOrNull() ?: return
val body = claims.body
val email = body["email"] as String
val nickname = body["nickname"] as String
val authorities = mutableListOf<GrantedAuthority>()
// 예를 들어, 클레임에서 roles를 추출하여 authorities에 추가하는 방법
// val roles = body["roles"] as List<String>
// roles.forEach { role -> authorities.add(SimpleGrantedAuthority(role)) }
val authentication = JwtAuthenticationToken(token, email, nickname, authorities)
SecurityContextHolder.getContext().authentication = authentication
}
chain.doFilter(request, response)
}
}
이걸
@Component
class JwtAuthenticationFilter(
private val jwtPlugin: JwtPlugin,
) : OncePerRequestFilter() {
companion object {
private val BEARER_PATTERN = Regex("^Bearer (.+?)$")
}
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain,
) {
val jwt = request.getBearerToken()
if (jwt != null) {
jwtPlugin.validateToken(jwt)
.onSuccess {
val userId = it.payload.subject.toLong()
val email = it.payload.get("email", String::class.java)
val userPrincipal = UserPrincipal(id = userId, email = email)
val details = WebAuthenticationDetailsSource().buildDetails(request)
val auth = JwtAuthenticationToken(userPrincipal, details)
SecurityContextHolder.getContext().authentication = auth
}
}
filterChain.doFilter(request, response)
}
private fun HttpServletRequest.getBearerToken(): String? {
val headerValue = this.getHeader(HttpHeaders.AUTHORIZATION) ?: return null
return BEARER_PATTERN.find(headerValue)?.groupValues?.get(1)
}
}
이렇게 userprincipal을 넣어서 인식을 하게 만들었다.
그런데 스웨거에서 회원가입에도 jwt 인증이 필요하다고 하길래 확인한 결과,
시큐리티컨피스에서
it.requestMatchers(
"/admins/signup", "/admins/signin", "/swagger-ui/**", "/v3/api-docs/**", "/oauth2/login",
"/oauth2/callback/kaka
여기가 "/admins/signup", "/admins/signin"이 아니라 그냥 signup, signim이라서 인식이 안됬던거였기에 수정했다.
그리고 지금은 카톡 로그인 페이지에 에러가 뜨는걸 해결하는 중이다.