An HTTP filter intercepts a request, performs focused processing, and either forwards it to the next filter or ends the exchange. Spring Security assembles filters into an ordered chain, allowing each component to handle responsibilities such as authentication, authorization, CSRF protection, or CORS rules. section 5.0 section 5.1
A custom filter implements the jakarta.servlet.Filter interface and overrides doFilter(ServletRequest, ServletResponse, FilterChain). The request supplies input, the response can be changed, and filterChain.doFilter(request, response) forwards processing. Omitting that call stops the chain. section 5.1
Use a filter when request processing must happen at a precise point:
- Validate a required Request-Id header before authentication; return HTTP 400 Bad Request when it is missing or blank. section 5.2
- Insert a custom filter before an existing filter with HttpSecurity.addFilterBefore(). section 5.2
- Insert a filter after an existing filter with addFilterAfter(), for example to log requests that pass authentication. section 5.3
- Choose the simplest implementation that meets the requirement; use GenericFilterBean or OncePerRequestFilter only when their added behavior is needed. section 5.5
Reject malformed requests before authentication
A RequestValidationFilter reads the Request-Id header. If the value is absent or blank, it sets HttpServletResponse.SC_BAD_REQUEST and returns. Otherwise, it calls filterChain.doFilter(request, response). Register it with addFilterBefore(new RequestValidationFilter(), BasicAuthenticationFilter.class) in a SecurityFilterChain bean. A request without the header returns 400; a request carrying Request-Id:12345 reaches the endpoint. section 5.2
Avoid duplicate authentication logging
An AuthenticationLoggingFilter can log the Request-Id after BasicAuthenticationFilter. When repeated execution must be prevented, extend OncePerRequestFilter and implement doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain), forwarding after logging. section 5.3 section 5.5
Figure 5.1 The request is passed to the filter chain. Every filter engages a manager to execute particular logic upon the request and then passes it down the line to the subsequent filter in the chain.
Visualizes the request moving through managers and successive filters in the chain. section 5.0


