The security filter chain
How a request is authenticated, the SecurityContext, AuthenticationManager and providers, and the order of filters that decides everything.
Spring Security is a chain of servlet filters sitting in front of your application, and almost every "why is this 403" question is answered by knowing which filter did it and in what order.
The chain is not a metaphor. You can print it.
Sixteen filters you did not ask for
Add spring-boot-starter-security to an otherwise ordinary application, write no configuration at all, and this is what is installed:
### Spring Security installed 1 chain(s)
### chain 1 has 16 filters, in this order:
### 1. DisableEncodeUrlFilter
### 2. WebAsyncManagerIntegrationFilter
### 3. SecurityContextPersistenceFilter
### 4. HeaderWriterFilter
### 5. CsrfFilter
### 6. LogoutFilter
### 7. UsernamePasswordAuthenticationFilter
### 8. DefaultLoginPageGeneratingFilter
### 9. DefaultLogoutPageGeneratingFilter
### 10. BasicAuthenticationFilter
### 11. RequestCacheAwareFilter
### 12. SecurityContextHolderAwareRequestFilter
### 13. AnonymousAuthenticationFilter
### 14. SessionManagementFilter
### 15. ExceptionTranslationFilter
### 16. FilterSecurityInterceptorYou can print your own the same way — the chain is a bean:
@Bean CommandLineRunner printChain(@Qualifier("springSecurityFilterChain") Filter f) {
return args -> ((FilterChainProxy) f).getFilterChains()
.forEach(c -> c.getFilters().forEach(x -> System.out.println(x.getClass().getSimpleName())));
}Four positions in that list explain most of the behaviour:
- 3.
SecurityContextPersistenceFilter— loads theSecurityContext(from the session, if there is one) at the start of the request and clears it at the end. This is whySecurityContextHolder.getContext()works anywhere in your code and why it is empty in a thread you spawned yourself. - 13.
AnonymousAuthenticationFilter— if nothing authenticated the request, it installs an anonymousAuthenticationrather than leavingnull. That is why your code can callgetAuthentication().getName()without a null check, and why "is the user logged in" is nevergetAuthentication() != null. - 15.
ExceptionTranslationFilter— catches the exceptions thrown by the filter after it and turns them into responses: 401 with a challenge if nobody is authenticated, 403 if somebody is and may not. - 16.
FilterSecurityInterceptor— last, and this is where authorisation happens. Everything above it runs before any URL rule is consulted.
That ordering is the mental model worth keeping: authenticate early, authorise last, and translate the result on the way out.
The chain is built from your configuration
Write a config and filters disappear:
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(STATELESS).and()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers(HttpMethod.GET, "/admin/**").hasRole("ADMIN")
.anyRequest().authenticated().and()
.httpBasic();### chain 1 has 12 filters, in this order:
### 1. DisableEncodeUrlFilter
### 2. WebAsyncManagerIntegrationFilter
### 3. SecurityContextPersistenceFilter
### 4. HeaderWriterFilter
### 5. LogoutFilter
### 6. BasicAuthenticationFilter
### ...Four gone. CsrfFilter, because CSRF was disabled. The three form-login filters, because no form login was requested. The chain is a product of your configuration, not a fixed pipeline you configure around — which is why "add a filter" and "which order does it go in" are real questions with real answers.
401 and 403, demonstrated
The distinction the authorisation lesson insisted on is exactly what ExceptionTranslationFilter implements:
public, no credentials -> HTTP 200
private, no credentials -> HTTP 401
private, as ana -> HTTP 200
/admin, as ana (ROLE_USER) -> HTTP 403
/admin, as root (ROLE_ADMIN) -> HTTP 200401 means I do not know who you are and comes with a challenge — WWW-Authenticate: Basic realm="Realm". 403 means I know, and you may not. A client can act on that difference: 401 means sign in, 403 means stop asking.
Matcher order decides everything
authorizeRequests rules are evaluated in the order written, first match wins. Spring Security refuses the most obvious version at startup — an antMatchers after anyRequest() fails with "Can't configure antMatchers after anyRequest" — but two ordinary path rules in the wrong order are accepted without a word, and that is the most common configuration bug in Spring Security:
// WRONG: /admin/** matches first, so the stricter users rule is unreachable
.antMatchers("/admin/**").authenticated()
.antMatchers("/admin/users/**").hasRole("ADMIN")Put specific patterns first and anyRequest() last, always. And make anyRequest() .authenticated() or .denyAll() — never leave it out, because a URL matching no rule is a URL with no protection. Default-deny, from the security fundamentals lesson, is a property you have to configure.
Stateless, and what it actually turns off
SessionCreationPolicy.STATELESS is what an API wants, and the effect is visible:
default config: Set-Cookie: JSESSIONID=AEA288FE...; Path=/; HttpOnly
STATELESS config: (no Set-Cookie at all)No session is created and none is read, so every request must carry its own credentials. That is right for an API with token or basic authentication, and it is also what makes CSRF protection unnecessary — which is the reason csrf().disable() appears beside it rather than as an independent choice. The CORS and CSRF lesson takes that decision apart properly.
Headers you get for free
HeaderWriterFilter at position 4 adds these without being asked:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0nosniff stops a browser guessing a content type it was not given. X-Frame-Options: DENY prevents your pages being framed, which is clickjacking prevention. The cache headers stop an authenticated response being stored.
Worth knowing because the usual way people meet these is by turning them off to fix something — an embed that needs framing, a response that should be cached. Change the one you need and leave the rest.
AuthenticationManager, providers and UserDetailsService
The authentication filters do not check credentials themselves. They build an Authentication object and hand it to the AuthenticationManager, which asks each configured AuthenticationProvider whether it can handle it.
For username and password that provider is DaoAuthenticationProvider, which uses two beans you supply:
@Bean PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
@Bean UserDetailsService users(PasswordEncoder enc) {
return new InMemoryUserDetailsManager(
User.withUsername("ana").password(enc.encode("secret")).roles("USER").build(),
User.withUsername("root").password(enc.encode("secret")).roles("USER","ADMIN").build());
}In a real system UserDetailsService loads from your database, and the password it returns is the stored bcrypt hash from the password lesson — the provider calls matches(), never equals().
Note roles("USER") produces the authority ROLE_USER. That prefix is the whole difference between hasRole("USER") and hasAuthority("ROLE_USER"), and it is why a URL rule written hasRole("ROLE_USER") is refused at startup — the prefix is added for you. The failure that really is silent runs the other way: authorities granted without the ROLE_ prefix (from a JWT's scope claim, say), which no hasRole check will ever match.
Under the hood: FilterChainProxy's dispatch, and where SecurityContextHolder actually lives
The name at the top of that printout — springSecurityFilterChain — is not a list, it is a bean called FilterChainProxy. The servlet container knows nothing about Spring Security; it only knows one Filter, a DelegatingFilterProxy registered under that name, and it calls that filter for every request that reaches the container. DelegatingFilterProxy does nothing but look up FilterChainProxy in the application context and hand the request to it. FilterChainProxy itself holds a list of SecurityFilterChains, each with a RequestMatcher; for a given request it walks that list, picks the first chain whose matcher matches, and runs only that chain's filters — which is why a multi-chain configuration (an API chain matched on /api/**, a form-login chain for everything else) is really just several independent filter lists gated by "does this request even belong to me," decided before a single security filter in either list runs.
Running "that chain's filters" is not a loop that calls each filter in turn — it is nested, nesting is the mechanism that makes ExceptionTranslationFilter at position 15 able to catch what FilterSecurityInterceptor at position 16 throws. FilterChainProxy builds a VirtualFilterChain whose doFilter() calls filter N, passing itself (advanced to N+1) as the FilterChain argument; filter N's own code runs, and whatever it does after calling chain.doFilter(request, response) only runs once every filter after it — including the real DispatcherServlet at the very end — has returned. That is exactly why an exception thrown deep inside FilterSecurityInterceptor surfaces as a 401 or 403 rather than a stack trace: ExceptionTranslationFilter wraps its call to chain.doFilter() in a try/catch, and everything downstream, including the interceptor and the controller, runs inside that try. The "Try it yourself" exercise below traces the same onion structure with three toy filters, because the nesting order — not the list order — is the thing worth being able to predict.
SecurityContextHolder is a ThreadLocal by default (MODE_THREADLOCAL), which is the whole reason SecurityContextHolder.getContext().getAuthentication() works from anywhere in your code without the Authentication being passed as a parameter down every call — it is reading state parked on the current thread, set once near the top of the filter chain. That convenience has a cost the chain has to pay explicitly. First, a ThreadLocal does not automatically follow the request onto a different thread: hand work to a raw ExecutorService, or spin up your own Thread, and the code running there sees an empty context, because nothing copied it. WebAsyncManagerIntegrationFilter, at position 2 — before SecurityContextPersistenceFilter even runs — exists to close exactly one instance of this gap: it propagates the context across Spring MVC's own async request handling for a controller returning a Callable, and only that path (Spring Security's reference documentation is explicit that there is no automatic integration for a DeferredResult, which your own code completes on a thread of its choosing); a CompletableFuture.supplyAsync(...) on a different executor, or a plain @Async method, is on its own unless you wire a DelegatingSecurityContextExecutor around it. Second, and more important operationally: the thread the container just used for this request is a pooled thread, and the pool will hand that same thread to a completely unrelated request next. If nothing cleared the ThreadLocal, the next request's code would start with the previous caller's Authentication still sitting there — a real leak of one user's identity into another user's request, not a style issue. That is why the filter at that position (SecurityContextPersistenceFilter historically; SecurityContextHolderFilter is the newer name for the same responsibility, paired with explicit saving through a SecurityContextRepository) loads the context at the start of the request and clears it in a finally block that runs no matter how the request ends — success, an exception translated by ExceptionTranslationFilter, or an exception nobody caught at all.
Try it yourself
Predict the order three nested filters actually print in
FilterChainProxy does not call filters in a flat loop — each filter wraps the next, the way the lesson's "Under the hood" section describes. Before running this, work out: does chain.run() print the three "before" lines and the three "after" lines in the same order, or the reverse?
List<String> log = new ArrayList<>();
List<Consumer<Runnable>> filters = new ArrayList<>();
filters.add(next -> { log.add("F1 before"); next.run(); log.add("F1 after"); });
filters.add(next -> { log.add("F2 before"); next.run(); log.add("F2 after"); });
filters.add(next -> { log.add("F3 before"); next.run(); log.add("F3 after"); });
Runnable chain = () -> log.add("controller");
for (int i = filters.size() - 1; i >= 0; i--) {
Runnable next = chain;
Consumer<Runnable> filter = filters.get(i);
chain = () -> filter.accept(next);
}
chain.run();
System.out.println(String.join("\n", log));Why the "after" lines come back in reverse
Each filter's "after" code only runs once next.run() returns, and next is whatever is nested inside it — for F1, that is "F2 wrapping F3 wrapping the controller." So F1's "after" line cannot print until everything nested inside F1 has finished completely, including F2's own "after" line and F3's own "after" line. The result is a stack, not a queue: first in, last out. This is precisely the shape that lets ExceptionTranslationFilter, sitting before FilterSecurityInterceptor in the written order, catch an exception the interceptor throws — the interceptor runs nested inside ExceptionTranslationFilter's own try/catch, exactly like controller runs nested inside F3, F2 and F1 above.
Misconceptions
- "The filter list runs in a
forloop, so filter order only matters for who runs first." It also decides who runs last on the way out — each filter's post-processing code sees the response only after every filter below it has already handled it, in reverse of the written order. That is the mechanic, not just the fact, behindExceptionTranslationFiltercatching whatFilterSecurityInterceptorthrows two positions later in the list. - "
SecurityContextHolderis basically a static field, so it's the same value everywhere." It defaults to aThreadLocal, which is a different value per thread, not a shared one — the entire reason it has to be reloaded at the start of a request and cleared at the end, and the entire reason it goes empty the moment work moves to a thread nobody explicitly copied it onto.
Sources
- Spring Security Reference — Architecture (
DelegatingFilterProxy,FilterChainProxy,SecurityContextHolderandSecurityContextRepository). - Spring Security Reference — Servlet Authentication Architecture (
SecurityContextPersistenceFilter/SecurityContextHolderFilter). - Spring Framework Reference — Async Requests (
WebAsyncManagerIntegrationFilterand thread-bound context propagation).