Spring Security Filter Chain: How Every Request Is Checked
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:
FilterChainProxyfinds the firstSecurityFilterChainwhose matcher accepts the request.SecurityContextHolderFilterloads theSecurityContextsaved by an earlier request (for example in the HTTP session) intoSecurityContextHolder.CsrfFilterrejects state-changing requests without a valid token.- Authentication filters, such as
BasicAuthenticationFilterorUsernamePasswordAuthenticationFilter, 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. AnonymousAuthenticationFilterputs an anonymous user in the context when nobody logged in, so later filters always have anAuthenticationto inspect.ExceptionTranslationFilterwraps the rest of the chain. If anything after it throws anAuthenticationExceptionorAccessDeniedException, it converts that into a 401 challenge or a 403 response.AuthorizationFilter, the last filter, evaluates yourauthorizeHttpRequestsrules. If the rule passes, the request finally reaches theDispatcherServlet.
4. Important Filters and What They Do
| Filter | Added by | Responsibility |
|---|---|---|
DisableEncodeUrlFilter | Always | Stops session IDs from being written into URLs |
WebAsyncManagerIntegrationFilter | Always | Makes the security context available to async request processing |
SecurityContextHolderFilter | Always | Loads the saved SecurityContext for this request |
HeaderWriterFilter | headers(), on by default | Adds security response headers |
CsrfFilter | csrf(), on by default | Validates the CSRF token on unsafe methods |
LogoutFilter | logout(), on by default | Handles POST /logout |
UsernamePasswordAuthenticationFilter | formLogin() | Processes the login form submission |
BasicAuthenticationFilter | httpBasic() | Reads Authorization: Basic ... |
BearerTokenAuthenticationFilter | oauth2ResourceServer() | Reads and validates Authorization: Bearer ... |
RequestCacheAwareFilter | Always | Restores a request saved before a login redirect |
SecurityContextHolderAwareRequestFilter | Always | Makes servlet methods such as request.isUserInRole() use Spring Security |
AnonymousAuthenticationFilter | On by default | Supplies an anonymous Authentication |
ExceptionTranslationFilter | Always | Turns security exceptions into 401 or 403 |
AuthorizationFilter | authorizeHttpRequests() | 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());
}
}
package com.javabytechie.filterchain;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import jakarta.servlet.Filter;
import org.springframework.security.web.SecurityFilterChain;
@Component
public class FilterChainPrinter implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(FilterChainPrinter.class);
private final List<SecurityFilterChain> chains;
public FilterChainPrinter(List<SecurityFilterChain> chains) {
this.chains = chains;
}
@Override
public void run(ApplicationArguments args) {
for (SecurityFilterChain chain : chains) {
List<Filter> filters = chain.getFilters();
log.info("Security filter chain with {} filters:", filters.size());
for (int i = 0; i < filters.size(); i++) {
log.info(" {}. {}", i + 1, filters.get(i).getClass().getSimpleName());
}
}
}
}
package com.javabytechie.filterchain;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ParcelController {
@GetMapping("/api/parcels/{id}")
public Map<String, String> track(@PathVariable String id) {
return Map.of("parcel", id, "status", "OUT_FOR_DELIVERY", "hub", "Pune-East");
}
}
package com.javabytechie.filterchain;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ParcelApplication {
public static void main(String[] args) {
SpringApplication.run(ParcelApplication.class, args);
}
}
logging:
level:
# TRACE shows every filter a request passes through. Use it only while debugging.
org.springframework.security: TRACE
6. Step-by-Step Code Explanation
apiChainis aSecurityFilterChainbean. Because it declares nosecurityMatcher, it applies to every request.httpBasic()addsBasicAuthenticationFilter, andauthorizeHttpRequests()addsAuthorizationFilter./erroris permitted so that Spring Boot's error page can report the real status of a rejected request instead of triggering a second login challenge.FilterChainPrinterreceives everySecurityFilterChainbean 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.- Setting
org.springframework.securitytoTRACEmakesFilterChainProxylog 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):
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:
$ 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
| Advantages | Limitations |
|---|---|
| Security runs before any controller, for every request type | Long chains are hard to read until you learn the standard order |
| Each mechanism is a separate, replaceable filter | A filter in the wrong position fails quietly, for example running before the user is known |
| Several chains can secure different URL areas differently | Only the first matching chain runs, so order between chains matters |
| Trace logging shows exactly where a request stopped | Trace 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 throughhttp.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 beforeUsernamePasswordAuthenticationFilter. - Forgetting the error dispatch. Permit
/errorso a 403 or 400 is not turned into a confusing 401.
10. Summary
FilterChainProxyselects oneSecurityFilterChainper request and runs its filters in order.- Early filters load the saved login and apply exploit protection; middle filters authenticate;
AuthorizationFilterruns last. ExceptionTranslationFilterconverts security exceptions into 401 or 403 responses.- Every
HttpSecurityDSL method adds or configures specific filters. - Inject
List<SecurityFilterChain>or enable TRACE logging to see the real chain.
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between FilterChainProxy and SecurityFilterChain?
FilterChainProxy is the single filter registered with the servlet container. It holds one or more SecurityFilterChain objects and, for each request, runs the filters of the first chain whose request matcher matches.
Q2. In which order do Spring Security filters run?
The order is fixed by Spring Security. Context loading (SecurityContextHolderFilter) and exploit protection (HeaderWriterFilter, CsrfFilter) come first, then authentication filters, then AnonymousAuthenticationFilter, ExceptionTranslationFilter and finally AuthorizationFilter.
Q3. How can I see which filters are in my security filter chain?
Set logging.level.org.springframework.security=TRACE to log each filter as a request passes, or inject List<SecurityFilterChain> and print getFilters() for each chain.
Q4. Which filter returns 401 and which returns 403?
ExceptionTranslationFilter returns 401 (through the authentication entry point) when an anonymous user is denied, and 403 (through the access denied handler) when a logged-in user lacks permission. Authentication filters such as BasicAuthenticationFilter can also return 401 directly for bad credentials.
Q5. Why does my custom filter run twice?
A Filter declared as a Spring bean is registered automatically with the servlet container, in addition to its place in the security chain. Disable the automatic registration with a FilterRegistrationBean whose setEnabled(false) is called, or do not make the filter a bean.