What is the purpose of the Spring Security filter chain, and how do you add or customize a filter in it?
The Spring Security filter chain is an ordered sequence of servlet filters that each handle one aspect of request processing—like extracting credentials, checking CSRF tokens, or enforcing authorization—before the request reaches the application's controllers.
Key Points
Filters run in a defined order; earlier filters (like UsernamePasswordAuthenticationFilter) handle authentication before later ones enforce authorization.
Each filter has a narrow responsibility, which keeps the pipeline modular and easier to reason about.
Custom filters can be inserted using addFilterBefore(), addFilterAfter(), or addFilterAt(), specifying their position relative to an existing filter.
A custom filter typically extends OncePerRequestFilter to guarantee it executes exactly once per request.
Misordering a custom filter (e.g., placing a JWT filter after the authorization check) can silently break security, so exact placement matters.
Example
A custom JwtAuthFilter is added with addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) so token validation happens before Spring Security's standard authentication processing runs.
Adding a custom filter as a @Component as well as in the security chain, so it runs twice (once as a normal servlet filter).
Placing a JWT filter after the authorization filter, so requests are rejected before the token is read.
Follow-up Questions
How do you add a filter at the right place? Use http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class).
Can you have more than one filter chain? Yes, define several SecurityFilterChain beans with different securityMatcher() rules and @Order.
Interview Tip
A concise interview answer is
The filter chain is an ordered pipeline of filters, each responsible for one piece of security processing like authentication or authorization, that a request passes through before reaching the controller. To add a custom filter—say for JWT validation—I'd use addFilterBefore() or addFilterAfter() to place it precisely relative to an existing filter.