Explain the purpose of the Spring Security filter chain and how you would add or customize a filter within 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.

Code Example:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

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."