Sub topic 2
How requests flow through the security filter chain
This chapter assumes you can build a Spring Boot REST controller, read Java lambdas and annotations, and define @Bean methods. It also assumes you know HTTP methods, status codes and headers. Here you will learn what happens to a request between the servlet container and your controller, and which parts of that path Spring Security controls.
Why a filter chain
Spring Security protects a web application with servlet filters. A servlet filter is a component that sees every request before the servlet does, and sees the response on the way out. It can inspect the request, change it, stop it, or pass it along.
Spring MVC routes requests through a single servlet, the DispatcherServlet. Security checks must run before that servlet, so your controllers never see a request that was not allowed. Filters sit in front of the servlet, which makes them the right place for this job.
Spring Security does not register dozens of filters with the servlet container. It registers one, and that one delegates to a list of security filters. The pieces are:
DelegatingFilterProxyis a servlet filter that the container knows about. In Spring Boot, a similar registration bean,DelegatingFilterProxyRegistrationBean, sets it up for you. It looks up a Spring bean and hands each request to it.FilterChainProxyis that Spring bean. It is the real entry point of Spring Security. It holds one or moreSecurityFilterChainobjects and picks the one that matches the current request.SecurityFilterChainis an ordered list of security filters, plus a rule saying which requests it applies to.
Because the work happens in a Spring bean, the security filters can use dependency injection like any other bean.
Choosing a chain
An application can define several SecurityFilterChain beans. For each request, FilterChainProxy tests the chains in order and uses the first one whose request matcher accepts the request. It runs only that chain. The other chains are ignored for this request.
This has a practical consequence. If you define two chains, the more specific one must come first, or the broader one will capture every request. You control the order with the @Order annotation on the bean methods.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class TwoChainsConfig {
@Bean
@Order(1)
SecurityFilterChain adminChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/admin/**")
.authorizeHttpRequests(auth -> auth.anyRequest().hasRole("ADMIN"))
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain defaultChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}The first chain calls securityMatcher("/api/admin/**"), so it applies only to admin paths. The second has no matcher, so it matches everything else. If you swapped the @Order values, the default chain would match admin requests first and the admin rule would never run.
If you define only one chain, you do not need @Order or securityMatcher. That is the case in most APIs, and the rest of this tutorial uses a single chain.
What the filters in a chain do
The chain is an ordered list, and the order matters because later filters depend on work done by earlier ones. You do not normally write this list yourself. Calls such as http.csrf(...), http.httpBasic(...) and http.oauth2ResourceServer(...) add or configure filters, and Spring Security puts each one in its correct position.
A typical chain for a Spring Boot API contains filters like these, in this relative order:
| Filter | Purpose |
|---|---|
| `DisableEncodeUrlFilter` | Stops session IDs from being added to URLs. |
| `SecurityContextHolderFilter` | Loads the `SecurityContext` for the request and clears it afterward. |
| `HeaderWriterFilter` | Adds security response headers. |
| `CorsFilter` | Handles CORS, if you called `http.cors(...)`. |
| `CsrfFilter` | Rejects unsafe requests that lack a valid CSRF token, unless CSRF is disabled. |
| `LogoutFilter` | Handles logout requests. |
| `BasicAuthenticationFilter` | Reads the `Authorization: Basic` header and authenticates the caller. |
| `BearerTokenAuthenticationFilter` | Reads the `Authorization: Bearer` header when you configure a resource server. |
| `RequestCacheAwareFilter` | Restores a saved request after a login redirect. |
| `AnonymousAuthenticationFilter` | Gives unauthenticated requests an anonymous identity. |
| `ExceptionTranslationFilter` | Turns security exceptions into 401 or 403 responses. |
| `AuthorizationFilter` | Makes the final access decision for the request. |
The exact list depends on your version and configuration. You never need to memorize it. Three points are worth understanding well.
- Authentication filters come before authorization. A filter such as
BasicAuthenticationFilterworks out who the caller is. TheAuthorizationFilterat the end decides whether that caller may proceed. This is the split between authentication and authorization applied to the request path. ExceptionTranslationFiltersits just beforeAuthorizationFilter. It catches exceptions thrown byAuthorizationFilterand by your own code further down the chain. It does not catch exceptions thrown by earlier filters.- If every filter passes, the request continues to the servlet. The last filter calls
chain.doFilter(...), and only then does theDispatcherServletsee the request.
Seeing the chain in your own application
You can print the real chain for your application. Turn on debug logging for the filter chain proxy in application.properties:
logging.level.org.springframework.security=DEBUGAt startup, and on each request, Spring Security logs the filters it applies, for example Will secure any request with [DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, ...]. Read this output when a request behaves in a way you did not expect. It shows which filters are present, and which are missing because you disabled them.
Setting spring.security logging to DEBUG is for development. In production it adds noise and can log request details you would rather not store.
A request in motion
The sequence below follows a protected request that carries a valid Basic header, and then one that lacks credentials.
In the second request, the caller is not rejected by an authentication filter. Instead, AnonymousAuthenticationFilter marks the request as anonymous, and AuthorizationFilter denies access because the rule requires an authenticated user. ExceptionTranslationFilter catches that denial. It sees an anonymous caller, so it starts the authentication entry point, which for HTTP Basic sends 401 with a WWW-Authenticate header. If the caller were authenticated but lacked the role, the same filter would send 403 instead.
That distinction answers a common question. A 401 means the system does not know who you are. A 403 means it knows who you are and says no.
Edge cases and common errors
Requests that skip your chain. Security rules apply only to requests that the chain handles. If no chain matches a request, it is not protected by your configuration. Using anyRequest() in the last rule of a single chain avoids this gap.
Ordering of multiple chains. If two chains have the same @Order value, startup fails. If you omit @Order on several chains, Spring cannot tell which is first and also fails. Always number them.
Filters you add yourself. You can insert a custom filter with addFilterBefore, addFilterAfter or addFilterAt. Position it relative to a known filter class. A custom token filter, for instance, usually goes before UsernamePasswordAuthenticationFilter or BasicAuthenticationFilter.
http.addFilterBefore(new ApiKeyFilter(), BasicAuthenticationFilter.class);Here ApiKeyFilter is your own class. A servlet filter that you also declare as a Spring @Component is registered with the servlet container too, so it can run twice, once outside Spring Security and once inside the chain. To prevent that, do not annotate it as a component, or add a FilterRegistrationBean that disables its automatic registration.
Forwards and error dispatches. Servlet containers can dispatch a request internally, for instance to /error when a controller throws an exception. In recent Spring Security versions, authorization applies to these dispatches as well. If /error requires authentication, a failed request may come back as 401 or 403 instead of the real error body. The usual fix is to permit /error in your rules.
Static resources and web.ignoring. You can exclude a path from the whole chain with a WebSecurityCustomizer. That removes every security filter for the path, including headers, so use it only for truly static content. For API endpoints that should be public, use permitAll() inside the chain instead, so the other filters still run.
Summary of the model
- The servlet container sees one filter,
DelegatingFilterProxy, which delegates toFilterChainProxy. FilterChainProxyselects the firstSecurityFilterChainthat matches the request and runs its filters in order.- Authentication filters establish the caller's identity.
AuthorizationFilterdecides access.ExceptionTranslationFilterconverts a denial into 401 or 403. - You configure the chain through
HttpSecurityin aSecurityFilterChainbean. The next chapter shows how to define that bean.
Exercise
You define two SecurityFilterChain beans. The first has no securityMatcher and requires authentication for any request. The second has securityMatcher("/public/**") and permits all. Requests to /public/info still return 401. Why, and how do you fix it?
Show answer
FilterChainProxy runs only the first chain whose matcher accepts the request. The first chain has no matcher, so it matches every request, including /public/info, and the second chain is never used. Fix it by giving the specific chain a lower @Order value than the general chain (for example @Order(1) on the /public/** chain and @Order(2) on the general one), or by adding a securityMatcher to the general chain so it no longer matches everything.
Exercise
A request has no credentials and reaches a rule that requires authentication. Which filter turns the denial into a 401 response, and why is the response 401 and not 403?
Show answer
ExceptionTranslationFilter does it. AuthorizationFilter denies the request, and the exception is caught by ExceptionTranslationFilter. Because the caller is anonymous, it calls the authentication entry point, which sends 401. If the caller were authenticated but lacked permission, it would send 403 through the access denied handler.