오늘은 프로젝트 2일차..
프로젝트 시작하고 모르는게 많아서 의문이 생기면 찾아보느라 시간 가는 줄 모르겠다 ㅋㅋ
오늘은 그 중 하나인 JWT 필터를 구현하는 과정에서 생긴 의문을 정리해보려한다.
이전에 배운 코드에서 JwtAuthenticationFilter는 UsernamePasswordAuthenticationFilter를 상속받고, JwtAuthorizationFilter는 OncePerRequestFilter를 상속받은 걸 봤다. 그럼 왜 이렇게 차이를 두었을까?
JWT는 상태가 없는 (stateless) 인증 방식으로 매 요청마다 토큰을 확인해야 한다. 즉, 사용자가 요청할 때마다 헤더에서 JWT 토큰을 추출하고 검증해야 하며, 이를 통해 인증 정보를 설정해야 한다. OncePerRequestFilter는 매 요청마다 한 번만 실행되기 때문에, JWT 인증 필터 구현에 적합하다.
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
public JwtAuthenticationFilter(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = jwtUtil.resolveToken(request);
if (token != null && jwtUtil.validateToken(token)) { // 토큰 유효성 검사
Authentication authentication = jwtUtil.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
예외 처리
JwtAuthorizationFilter 역할
성능 고려