Filter는 Servlet의 핵심 구성 요소 중 하나로, 클라이언트의 요청(Request)과 응답(Response)을 가로채서 특정 작업을 수행할 수 있도록 해주는 기능이다.
[클라이언트] → [Filter] → [Servlet] → [Controller] → [응답 처리]
@WebFilter("/*")
public class CustomFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println(" Custom Filter 실행");
chain.doFilter(request, response); // 다음 필터 또는 컨트롤러로 전달
}
}
이렇게 Filter를 직접 구현하면 모든 요청을 가로채서 원하는 작업을 수행할 수 있다.
Spring Security는 보안 처리를 위한 자체적인 FilterChain을 제공하며, 기존의 Filter를 대체하여 인증 & 권한 관리를 자동화한다.
[클라이언트] → [Spring Security FilterChain] → [DispatcherServlet] → [Controller]
즉, Spring Security는 요청이 컨트롤러에 도달하기 전에, 보안 관련 필터를 통해 인증을 수행하고 요청의 유효성을 검사한다.
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
String jwt = authorizationHeader.substring(7);
Claims claims = jwtUtil.extractClaims(jwt);
setAuthentication(claims);
}
chain.doFilter(request, response);
}
private void setAuthentication(Claims claims) {
AuthUser authUser = new AuthUser(
Long.valueOf(claims.getSubject()),
claims.get("email", String.class),
UserRole.of(claims.get("role", String.class))
);
SecurityContextHolder.getContext().setAuthentication(new JwtAuthenticationToken(authUser));
}
}
Spring Security를 사용하면 기존의 Custom Filter 없이 보안 처리를 자동화할 수 있다.
| 구분 | Spring Security 없이 직접 구현 | Spring Security 사용 |
|---|---|---|
| 필터 실행 위치 | DispatcherServlet 이전 | DispatcherServlet 이전 (Security FilterChain) |
| 인증(Authentication) 방식 | 개발자가 직접 구현해야 함 | SecurityContextHolder를 통해 자동 관리 |
| JWT 검증 | 직접 필터에서 처리해야 함 | JwtAuthenticationFilter에서 자동 처리 |
| CORS / CSRF 보호 | 개발자가 직접 설정 | Spring Security가 자동 제공 |
| 필터 개수 | 필요할 때마다 직접 추가 | 기본적으로 여러 개의 필터 제공 |
| 유지보수 | 직접 관리해야 함 | Spring Security 설정만 조정하면 됨 |
즉, Spring Security는 기존의 Filter를 대체하여 인증 & 보안 처리를 자동화하며, 개발자가 직접 관리해야 하는 부담을 줄여준다.
JwtAuthenticationFilter를 Spring Security FilterChain에 추가하면 간단하게 처리 가능.