00:00

Spring Security Filter Chain: How Every Request Is Checked

Last updated:

The Spring Security filter chain is the ordered list of servlet filters that every HTTP request passes through before it reaches your controller. Each filter has one job, such as reading a password, loading the saved login or checking access rules, and any filter can stop the request early with a 401 or 403.

Knowing the order of these filters is the fastest way to debug "why is my request rejected?" problems. In this tutorial you will print the real filter list of a running application and follow one request through it with trace logging.

1. What Is the Spring Security Filter Chain?

A servlet filter is code that runs before (and after) a servlet handles a request. Spring Security registers one filter with the servlet container, FilterChainProxy, and that filter delegates to a list of security filters. This list is a SecurityFilterChain, and an application can have several of them for different URL patterns.

Each SecurityFilterChain contains a request matcher and an ordered list of filters. FilterChainProxy picks the first chain whose matcher fits the request, then runs only that chain's filters. How the servlet container hands requests to FilterChainProxy through DelegatingFilterProxy is covered in Spring Security architecture; this page focuses on what happens inside the chain.

2. Why Spring Security Uses a Chain of Filters

Security checks must run before any controller code, for every request, including requests for static files and error pages. Servlet filters are the only standard place that guarantees this, and they work the same way for Spring MVC, plain servlets and the error dispatch.

Splitting the work into small filters also keeps each piece replaceable. Adding JWT authentication means adding one filter; switching from form login to HTTP Basic means swapping one filter. Everything else, such as CSRF protection and exception handling, stays as it was.

3. How a Request Moves Through the Chain

Every filter receives the request, does its work, and either calls chain.doFilter(...) to pass the request on or writes a response itself and stops. The diagram shows the filters that matter most for a typical API secured with HTTP Basic:

Request flow through the main Spring Security filtersFilterChainProxy selects a SecurityFilterChain. The request then passes SecurityContextHolderFilter, CsrfFilter, BasicAuthenticationFilter, AnonymousAuthenticationFilter, ExceptionTranslationFilter and AuthorizationFilter before reaching the DispatcherServlet and controller. FilterChainProxy picks the first matching chain SecurityContextHolderFilter loads any saved login CsrfFilter checks POST, PUT, DELETE BasicAuthenticationFilter reads Authorization header AnonymousAuthentication Filter: fills in anonymous ExceptionTranslation Filter: turns errors into 401/403 AuthorizationFilter applies URL rules DispatcherServlet then your controller
Figure 1: filters run in a fixed order; authentication filters run before the authorization filter at the end.
  1. FilterChainProxy finds the first SecurityFilterChain whose matcher accepts the request.
  2. SecurityContextHolderFilter loads the SecurityContext saved by an earlier request (for example in the HTTP session) into SecurityContextHolder.
  3. CsrfFilter rejects state-changing requests without a valid token.
  4. Authentication filters, such as BasicAuthenticationFilter or UsernamePasswordAuthenticationFilter, look for credentials. If they find valid ones, they put an authenticated user into the context. If they find wrong ones, they answer 401 immediately.
  5. AnonymousAuthenticationFilter puts an anonymous user in the context when nobody logged in, so later filters always have an Authentication to inspect.
  6. ExceptionTranslationFilter wraps the rest of the chain. If anything after it throws an AuthenticationException or AccessDeniedException, it converts that into a 401 challenge or a 403 response.
  7. AuthorizationFilter, the last filter, evaluates your authorizeHttpRequests rules. If the rule passes, the request finally reaches the DispatcherServlet.

4. Important Filters and What They Do

FilterAdded byResponsibility
DisableEncodeUrlFilterAlwaysStops session IDs from being written into URLs
WebAsyncManagerIntegrationFilterAlwaysMakes the security context available to async request processing
SecurityContextHolderFilterAlwaysLoads the saved SecurityContext for this request
HeaderWriterFilterheaders(), on by defaultAdds security response headers
CsrfFiltercsrf(), on by defaultValidates the CSRF token on unsafe methods
LogoutFilterlogout(), on by defaultHandles POST /logout
UsernamePasswordAuthenticationFilterformLogin()Processes the login form submission
BasicAuthenticationFilterhttpBasic()Reads Authorization: Basic ...
BearerTokenAuthenticationFilteroauth2ResourceServer()Reads and validates Authorization: Bearer ...
RequestCacheAwareFilterAlwaysRestores a request saved before a login redirect
SecurityContextHolderAwareRequestFilterAlwaysMakes servlet methods such as request.isUserInRole() use Spring Security
AnonymousAuthenticationFilterOn by defaultSupplies an anonymous Authentication
ExceptionTranslationFilterAlwaysTurns security exceptions into 401 or 403
AuthorizationFilterauthorizeHttpRequests()Applies URL authorization rules

You do not create these filters yourself. Each DSL method on HttpSecurity adds, configures or removes one or more of them. To insert your own filter at a precise position, see custom security filter.

5. A Complete Example: Listing the Filters of a Parcel Tracking API

This small parcel tracking API, built with Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2, prints its own filter chain at startup. It then runs one request with Spring Security trace logging switched on, so you can watch each filter take its turn.

package com.javabytechie.filterchain;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/error").permitAll()
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        // Demo user only
        return new InMemoryUserDetailsManager(
            User.withUsername("priya").password(encoder.encode("priya-pass")).roles("COURIER").build());
    }
}

6. Step-by-Step Code Explanation

  1. apiChain is a SecurityFilterChain bean. Because it declares no securityMatcher, it applies to every request. httpBasic() adds BasicAuthenticationFilter, and authorizeHttpRequests() adds AuthorizationFilter.
  2. /error is permitted so that Spring Boot's error page can report the real status of a rejected request instead of triggering a second login challenge.
  3. FilterChainPrinter receives every SecurityFilterChain bean through constructor injection and logs the class name of each filter in order. Use this when you are unsure which filters a configuration really produced.
  4. Setting org.springframework.security to TRACE makes FilterChainProxy log each filter as it is invoked, numbered by position.

7. Expected Output

Starting the application and sending one authenticated request produced these log lines (timestamps and logger names removed):

Terminal
Security filter chain with 12 filters:
  1. DisableEncodeUrlFilter
  2. WebAsyncManagerIntegrationFilter
  3. SecurityContextHolderFilter
  4. HeaderWriterFilter
  5. CsrfFilter
  6. LogoutFilter
  7. BasicAuthenticationFilter
  8. RequestCacheAwareFilter
  9. SecurityContextHolderAwareRequestFilter
  10. AnonymousAuthenticationFilter
  11. ExceptionTranslationFilter
  12. AuthorizationFilter
Invoking DisableEncodeUrlFilter (1/12)
Invoking WebAsyncManagerIntegrationFilter (2/12)
Invoking SecurityContextHolderFilter (3/12)
Invoking HeaderWriterFilter (4/12)
Invoking CsrfFilter (5/12)
Invoking LogoutFilter (6/12)
Invoking BasicAuthenticationFilter (7/12)
DaoAuthenticationProvider: Authenticated user
Invoking RequestCacheAwareFilter (8/12)
Invoking SecurityContextHolderAwareRequestFilter (9/12)
Invoking AnonymousAuthenticationFilter (10/12)
Invoking ExceptionTranslationFilter (11/12)
Invoking AuthorizationFilter (12/12)
Secured GET /api/parcels/PX-7781

The startup list shows the exact chain for this configuration. Because there is no formLogin(), the form login filters are absent, while BasicAuthenticationFilter is present. The trace lines show the request visiting the filters in the same order. While BasicAuthenticationFilter runs, it asks the authentication manager to check the password, and DaoAuthenticationProvider logs the successful check. After AuthorizationFilter approves the request, FilterChainProxy logs Secured GET and hands the request to the controller.

The client sees the result of that walk. Without credentials, ExceptionTranslationFilter starts a Basic challenge. With a wrong password, BasicAuthenticationFilter rejects the request itself and the controller is never called:

Terminal
$ curl localhost:8080/api/parcels/PX-7781
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
{"timestamp":"2026-11-18T12:14:23.070Z","status":401,"error":"Unauthorized","path":"/api/parcels/PX-7781"}

$ curl -u priya:wrong localhost:8080/api/parcels/PX-7781
HTTP/1.1 401
{"timestamp":"2026-11-18T12:14:23.207Z","status":401,"error":"Unauthorized","path":"/api/parcels/PX-7781"}

8. Advantages and Limitations

AdvantagesLimitations
Security runs before any controller, for every request typeLong chains are hard to read until you learn the standard order
Each mechanism is a separate, replaceable filterA filter in the wrong position fails quietly, for example running before the user is known
Several chains can secure different URL areas differentlyOnly the first matching chain runs, so order between chains matters
Trace logging shows exactly where a request stoppedTrace logs are noisy and can include sensitive request details

9. Common Mistakes and Best Practices

  • Registering a security filter as a plain @Component. Spring Boot then adds it to the servlet container as well, so it runs twice: once outside the security chain and once inside. Add it through http.addFilterBefore(...) and disable the automatic registration.
  • Guessing the filter order. Print the chain, as in the example, or enable TRACE logging before changing anything.
  • Leaving TRACE logging on in production. It slows requests and may write headers to logs. Use it locally or for a short, controlled investigation.
  • Expecting authorization to see a user that a later filter creates. Custom authentication filters must run before AuthorizationFilter, typically before UsernamePasswordAuthenticationFilter.
  • Forgetting the error dispatch. Permit /error so a 403 or 400 is not turned into a confusing 401.

10. Summary

  • FilterChainProxy selects one SecurityFilterChain per request and runs its filters in order.
  • Early filters load the saved login and apply exploit protection; middle filters authenticate; AuthorizationFilter runs last.
  • ExceptionTranslationFilter converts security exceptions into 401 or 403 responses.
  • Every HttpSecurity DSL method adds or configures specific filters.
  • Inject List<SecurityFilterChain> or enable TRACE logging to see the real chain.

11. References