* 이전 포스팅에서 다루었던 JWT 토큰 기반 인증의 구현에 대한 포스팅입니다
0. Dispatch Type
- 서블릿 기반의 웹 애플리케이션에서 사용되는 개념
- 서블릿이나 필터가 어떤상황에서 요청을 처리하는 지 나타냄
Type | 설명 | 주요 사용 상황 | 관련 메서드/상황 |
REQUEST | 클라이언트로부터 직접 들어온 요청 | 브라우저에서 URL 입력 또는 링크 클릭 |
일반적인 요청 처리
|
FORWARD | 서버 내부에서 다른 리소스로 요청 전달 | 다른 서블릿이나 JSP로 제어를 넘길 때 |
RequestDispatcher.forward()
|
INCLUDE | 다른 리소스의 내용을 현재 응답에 포함 | 공통 헤더, 푸터, 메뉴 포함 등 |
RequestDispatcher.include()
|
ASYNC | 비동기적으로 처리되는 요청 | 서블릿 3.0 이상에서 비동기 처리 |
startAsync() 호출 후 처리
|
ERROR | 요청 처리 중 예외 발생 시 오류 페이지로 전달 | 404, 500 등 오류 응답 시 |
web.xml의 <error-page> 또는 @ExceptionHandler 등
|
1. OncePerRequestFilter
- OncePerRequestFilter는 Dispatch Type이 REQUEST, ASYNC인 타입에 대해서만 단 한번만 처리하는 필터입니다.
- JwtAuthenticationFilter는 토큰 기반 인증 검증 필터이므로 REQUEST 타입에서 한번만 동작하도록 구현하는데 적절합니다.
2. JwtAuthenticationFilter
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtProvider jwtProvider;
private final IJwtService jwtService;
private final HttpUtils httpUtils;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, AuthenticationException, JwtException {
String accessToken = httpUtils.resolveToken(request);
jwtProvider.validateToken(accessToken);
if (jwtService.isBlackList(accessToken)) {
throw new BlackListTokenException("black_list_token");
}
this.setAuthentication(accessToken);
filterChain.doFilter(request, response);
}
private void setAuthentication(String accessToken) {
Authentication authentication = jwtService.createAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
- JwtAuthenticationFilter는 토큰 기반 인증을 담당하는 필터입니다.
- JWT Token를 보안 헤더를 통해 서버에 요청합니다.
- JwtProvider가 JWT Token이 유효한지 검증합니다.
- JwtProvider가 JWT Token이 블랙리스트인지 확인합니다.
- 검증에 성공할 경우
- 인증된 Authentication 객체를 생성합니다.
- SecurityContextHolder의 SecurityContext에 생성된 Authentication 객체를 셋팅합니다.
- 검증에 실패할 경우
- AuthenticationException (AuthenticationEntryPoint에 의해 처리됩니다)
- 로그인 창으로 리다이렉트 됩니다.
- BlackListTokenException (AuthenticationEntryPoint에 의해 처리됩니다)
- RefreshToken이 무효화 됩니다.
- 로그인 창으로 리다이렉트 됩니다.
- AuthenticationException (AuthenticationEntryPoint에 의해 처리됩니다)
'Spring > Spring Security' 카테고리의 다른 글
[Spring Security][KoLiving] 4-4. RefreshToken Rotation (0) | 2023.10.03 |
---|---|
[Spring Security][KoLiving] 4-3. RefreshToken (2) | 2023.10.03 |
[Spring Security][KoLiving] 4. JWT 토큰 기반 인증 (0) | 2023.10.03 |
[JWT] 2-2. Practical Application: AccessToken과 RefreshToken (0) | 2023.10.03 |
[JWT] 1. Introduction (1) | 2023.10.03 |