❗이슈
문제
- /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)) {
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);
}
}