Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท Filter Chain and Configuration

The Spring Security Filter Chain, Step by Step

Follow a request through DelegatingFilterProxy, FilterChainProxy and the ordered security filters, and learn to read the filter list from the debug log.

Spring Security is a pipeline of servlet filters. Everything it does, from reading a Basic header to blocking a forged form post, happens inside a filter that runs before your controller. Once you can picture that pipeline and its order, almost every question of the form "why did this request get a 401 / a redirect / a 403?" has an obvious answer.

This lesson explains the three layers of the machinery, the order of the standard filters, and how to see the chain for a real request. The runnable examples build a chain of filters in plain Java so the control flow (call next, or stop) is clear.

Three layers

A request crosses three layers before it reaches Spring MVC:

  1. DelegatingFilterProxy is a normal servlet filter registered with the container (Boot registers it for you under the name springSecurityFilterChain). It does no security. Its only job is to hand the request to a Spring bean, so that the security filters can use dependency injection.
  2. FilterChainProxy is that bean. It owns a list of SecurityFilterChains. It asks each one "do you match this request?" and runs only the first that does. It also applies the HttpFirewall that rejects malformed URLs.
  3. SecurityFilterChain is a request matcher plus an ordered list of filters. Your SecurityFilterChain bean is one of these.
flowchart TB
  A["Servlet container"] --> B["DelegatingFilterProxy"]
  B --> C["FilterChainProxy<br/>(HttpFirewall first)"]
  C --> D{"Which SecurityFilterChain<br/>matches the request?"}
  D --> E["Chain 1: /api/**"]
  D --> F["Chain 2: everything else"]
  F --> G["Security filters in order"]
  G --> H["DispatcherServlet<br/>your controller"]

Only the first matching chain runs, never several.

The reason for this design is that the security filters are not registered in the servlet container individually. They live inside SecurityFilterChains, so a chain can contain different filters for different URLs, and the container sees just one filter.

The standard filters, in order

For a typical Boot application the chain contains (the exact list depends on what you enable):

Order Filter What it does
1 DisableEncodeUrlFilter Stops the session id from being added to URLs
2 WebAsyncManagerIntegrationFilter Carries the context into async request processing
3 SecurityContextHolderFilter Loads the SecurityContext (from the session) and clears it afterwards
4 HeaderWriterFilter Adds security response headers
5 CorsFilter Answers CORS preflight requests (when enabled)
6 CsrfFilter Validates the CSRF token on unsafe methods
7 LogoutFilter Handles POST /logout
8 UsernamePasswordAuthenticationFilter Processes POST /login
9 DefaultLoginPageGeneratingFilter, DefaultLogoutPageGeneratingFilter Generated pages
10 BasicAuthenticationFilter Reads Authorization: Basic ...
11 RequestCacheAwareFilter Replays the request saved before login
12 SecurityContextHolderAwareRequestFilter Makes request.isUserInRole work
13 AnonymousAuthenticationFilter Gives unauthenticated callers an "anonymous" identity
14 ExceptionTranslationFilter Turns security exceptions into 401/403 or a redirect
15 AuthorizationFilter Applies your authorizeHttpRequests rules

Two orderings are worth memorizing. Authentication filters come before authorization, because the rules need to know who is calling. And ExceptionTranslationFilter sits just before AuthorizationFilter, so it can catch the exception that the last filter throws. Placing a custom filter correctly means picking its position relative to these, which is the topic of custom filters.

How a filter works

A filter either passes the request on by calling chain.doFilter(request, response), or stops by writing a response itself and not calling it. Code before the call runs on the way in; code after it runs on the way out, while the stack unwinds. Notice that this is exactly how SecurityContextHolderFilter can clear the context at the end: it wraps the rest of the chain in a try ... finally.

In the real framework the filters, and the nested "virtual" chain of the chain proxy, behave like this one. The stand-in below creates three filters (authentication, exception translation, authorization) and a traced chain you can read.

Java Filters: call next, or stop the request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the output look at the order of the in/out lines: the filters are nested like parentheses. The authorization filter does not call next after throwing, so the controller never runs; the translation filter, which is outside it, catches the exception and builds the response. That is exactly the relationship in the real chain.

Seeing the real chain

Do not guess the order; print it. Set:

PROPERTIES
logging.level.org.springframework.security=DEBUG

and the first request of each kind logs something like:

TEXT
o.s.s.web.DefaultSecurityFilterChain : Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter, ... AuthorizationFilter

(The exact list depends on your version and configuration.) At TRACE level you also get one line per filter and per authorization decision, which is the fastest way to find out where a request stopped. The older @EnableWebSecurity(debug = true) prints a large report for every request and should never reach production because it logs request details.

Why the order matters: three classic bugs

  • A custom filter that reads the user too early. Placed before SecurityContextHolderFilter, it sees an empty context. Put it after the authentication filters.
  • A filter registered twice. If you declare your filter as a Spring @Bean, Boot also registers it with the servlet container, so it runs twice (once outside, once inside the chain). Do not make it a bean, or disable the registration.
  • Rules checked before authentication. Authorization is always last. If everyone is anonymous, the AuthenticationFilter you wrote never ran or was never added to the chain.

Which filters appear when

The filter list reflects your configuration. formLogin() adds UsernamePasswordAuthenticationFilter; httpBasic() adds BasicAuthenticationFilter; csrf adds CsrfFilter; oauth2ResourceServer adds BearerTokenAuthenticationFilter; oauth2Login adds OAuth2AuthorizationRequestRedirectFilter and OAuth2LoginAuthenticationFilter; sessionManagement adds SessionManagementFilter or session-related filters. Each configurer in the DSL adds or removes filters, a theme developed in the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many SecurityFilterChains does FilterChainProxy run for one request?

    The chain proxy iterates the chains and uses the first that matches; the others are ignored for that request.
  2. 2. Which filter turns an AccessDeniedException into a 403 response or a redirect to login?

    ExceptionTranslationFilter catches security exceptions thrown further down the chain (mainly by AuthorizationFilter) and translates them.
  3. 3. Your custom filter is declared as a @Bean and also added with addFilterBefore. What is the likely symptom?

    Boot registers filter beans in the servlet container too, so the filter runs once there and once inside the security chain.
  4. 4. What is the best way to find out which filters a request passed through?

    Security logging lists the chain and, at TRACE, each filter and each authorization decision.

Summary

  • The container sees DelegatingFilterProxy; it delegates to FilterChainProxy, which runs the first matching SecurityFilterChain.
  • Filters are nested: they run code before and after chain.doFilter, or stop the request by not calling it.
  • Authentication filters come first, then ExceptionTranslationFilter, then AuthorizationFilter.
  • The DSL configurers decide which filters are present; log at DEBUG/TRACE to see them.
  • Never register a security filter both as a bean and in the chain.

Next: The SecurityFilterChain bean and the lambda DSL