JWT토큰 형식 예외처리 문제

개발연습생log·2023년 1월 9일
0

Problem

목록 보기
4/4
post-thumbnail

❗이슈

문제

  • /api/v1/posts/my로 접속시 Security Filter에서 잘못된 형식의 토큰 예외처리가 제대로 되지 않는 문제가 발생

원인

  • JWTFilter에서 Bearer 처리가 잘 안된 것은 바로 필터에서 빠져나와 예외처리를 해주었지만 토큰의 형식이 잘못된 경우에는 바로 필터에서 빠져나오는 것이 아닌 인증 절차를 거치게 되어 예외처리가 제대로 처리되지 않았다.

해결

  • JwtFilter에서 토큰 형식을 검사하는 함수에 doFilter함수를 추가하여 토큰 형식이 잘못된 경우나 만료된 경우 바로 필터를 빠져나와 예외처리를 할 수 있도록 해주었다.
  • 코드
@RequiredArgsConstructor
@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    @Value("${jwt.token.key}")
    private String key;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        log.info("authorization : {}", authorization);

        if (authorization == null || !authorization.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = authorization.split(" ")[1];
        log.info("token : {}", token);

        if (!JwtUtil.isValidToken(request, token, key)) {
						//이것이 빠져있있다.(doFilter)
            filterChain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = JwtUtil.createAuthentication(token, key);

        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
profile
주니어 개발자를 향해서..

0개의 댓글