이 둘의 차이는 뭘까?
1)
String token = extractAccessToken(request);
String username = jwtUtil.validateToken(token).getSubject();
2)
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
1번 방식은 직접 JWT 토큰을 추출하고 검증하는 방식으로, JwtUtil을 사용하여 수동으로 토큰을 검증하고 사용자 정보를 얻습니다.
2번 방식은 Spring Security가 이미 처리한 인증 정보를 가져오는 방식입니다. 보통 Spring Security가 JWT를 처리하도록 설정되어 있다면, Authentication 객체에서 자동으로 인증 정보를 가져올 수 있습니다.
1번 쓸때
private String extractAccessToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
return token.substring(7); // "Bearer "를 제외한 부분만 반환
}
throw new CustomException(MemberErrorCode.INVALID_TOKEN);
}