Spring Security Architecture and the Filter Chain

Spring Security Architecture and the Filter Chain in Spring Boot: An airport channels every departing passenger through one screening hall laid out as a fixed…

The Analogy: An Airport Screening Hall's Fixed Line of Stations

An airport channels every departing passenger through one screening hall laid out as a fixed sequence of stations. First a boarding pass is scanned, then identity is checked, then bags go through the X-ray, then the passenger steps through the metal detector, and only after every station passes is the passenger released airside. The order is not arbitrary: the identity check must happen before the later stations, because the officers downstream assume the person in front of them has already been identified.

Each station does one job and hands the passenger to the next. A station can do only three things: wave the passenger through, stop them and turn them back, or note something and pass them on for a later station to judge. Because the stations run in a fixed order, where a check sits in the line decides what it can rely on. A station placed before the identity desk cannot know who the passenger is; a station placed after it can print their name on a slip. Move a check earlier or later and you change what information it has to work with, even though the check itself is unchanged.

The last station before the gate is the one that actually decides whether this passenger may board this flight. It reads the slip the earlier stations produced -- are you identified, are you cleared -- and matches it against the rule for the gate. If the passenger is not cleared it turns them back, and the turn-back comes in two very different forms: "we do not know who you are, go and get identified" versus "we know exactly who you are and you are not allowed on this flight". The earlier stations never make that final call; they only gather what the last station needs.

Now suppose the hall has more than one lane and an attendant sends each passenger to the first lane whose sign matches them. If someone hangs a broad "all passengers this way" sign on a fast lane and places it before the strict screening lane, every passenger matches the broad sign first and is sent down the fast lane -- the strict lane, however carefully staffed, never sees anyone. The hall is full of screening equipment and all of it is bypassed, not because a check failed, but because the lanes were ordered so the catch-all lane claimed everyone before the strict lane could.

Syntax or Core Structure

Spring Security is not something your controller calls. It is a chain of servlet filters that runs before the DispatcherServlet ever picks a controller. Each filter is a station in the screening hall: it inspects the request, then either lets it continue, stops it and writes a response, or records something for a later filter to judge. The filters run in a fixed, documented order, and a request that is rejected anywhere in the chain never reaches your code at all.

You declare the policy with a single SecurityFilterChain bean. The lambda configures which filters are active and what the final authorization rules are; the framework assembles the ordered chain for you.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

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

Consider a single request: GET /dashboard from a browser with no session and no credentials, against the rule anyRequest().authenticated(). The request enters the chain and is walked past each filter in order. The early filters find nothing to do -- it is a safe method, not a logout, not a login POST, and carries no Basic auth header -- so each passes it along. The ExceptionTranslationFilter does not decide anything; it simply wraps the downstream call so it can translate an exception into an HTTP response. The AuthorizationFilter at the end is where the decision is made: the request is anonymous, the rule requires authentication, so it throws, and the ExceptionTranslationFilter turns that into a 401 with a challenge.

Output:

step  filter       action
----------------------------------------
1     context      load context (anonymous)
2     csrf         skip (safe method)
3     logout       skip (not /logout)
4     formLogin    skip (not POST /login)
5     httpBasic    skip (no auth header)
6     exceptions   pass (guards downstream)
7     authorize    DENY (anonymous, auth required)
----------------------------------------
decided by   : authorize
translated by: exceptions
http status  : 401

The two roles are worth separating in your mind. The AuthorizationFilter is the station that turns the passenger back; the ExceptionTranslationFilter is the desk that converts "turned back" into a specific response -- a 401 to start authentication when nobody is logged in, or a 403 when a known user lacks the right. Your controller is never involved, which is exactly why a security rejection looks nothing like your @RestControllerAdvice output unless you wire it in deliberately.

Technical Depth: Ordering, Short-Circuiting, and Filter Placement

The chain is ordered, and the order is a contract

The filters are not a set; they are a list with a fixed relative order that Spring Security documents and keeps stable across versions. You rarely see the whole list, but you depend on it constantly. The table below shows the subset most policies touch, in the order they run, with the concrete servlet-filter class behind each short name used in the traces.

StepShort nameFilter classResponsibility
1contextSecurityContextHolderFilterLoads any saved context for the request
2csrfCsrfFilterRejects unsafe methods without a valid token
3logoutLogoutFilterHandles the logout endpoint
4formLoginUsernamePasswordAuthenticationFilterAuthenticates a login form POST
5httpBasicBasicAuthenticationFilterAuthenticates a Basic auth header
6exceptionsExceptionTranslationFilterTurns auth exceptions into 401 or 403
7authorizeAuthorizationFilterApplies the access rules, allow or deny

The authentication filters (steps 4 and 5) sit before the authorization filter (step 7) for a reason: authorization can only judge an identity that an earlier filter has already established. And the ExceptionTranslationFilter sits immediately before authorization so it is positioned to catch the exception the authorization filter throws.

Which filter short-circuits decides the status

A request does not always reach the end of the chain. A filter that rejects the request writes the response itself and stops the walk -- it short-circuits. The status you get depends on which filter that was. The following four requests are run against a policy that permits /public, requires authentication for /dashboard, and requires hasRole('ADMIN') for POST /orders, with CSRF protection on.

// walk each request until a filter short-circuits or authorization decides
for (Request r : requests) {
    if (r.unsafeMethod() && !r.csrfValid())      reject(r, "CsrfFilter", 403);
    else if (r.anonymous() && r.requiresAuth())  reject(r, "AuthorizationFilter", 401);
    else if (r.lacksRequiredRole())              reject(r, "AuthorizationFilter", 403);
    else                                          allow(r, "AuthorizationFilter", 200);
}

Output:

request                     method  csrf     decided by           status
------------------------------------------------------------------------
/dashboard                  GET     n/a      AuthorizationFilter  401
/orders                     POST    valid    AuthorizationFilter  403
/orders                     POST    missing  CsrfFilter           403
/public                     GET     n/a      AuthorizationFilter  200
------------------------------------------------------------------------
halted upstream of authz: 1
reached authorization   : 3

Two requests return 403 for completely different reasons. The POST /orders with a valid CSRF token reaches the AuthorizationFilter, which denies it because the user lacks the ADMIN role. The POST /orders with a missing token never gets that far: the CsrfFilter at step 2 short-circuits it. Same status code, different station, and if you are debugging by status code alone you will look in the wrong place.

Where you insert a custom filter decides what it can see

You add your own filters with addFilterBefore or addFilterAfter, naming an existing filter as the anchor. The insertion point is not cosmetic: a filter placed before the authentication filters runs while the request is still anonymous, so the SecurityContextHolder is empty; a filter placed at or after the authentication filters can read the established principal.

// after an authentication filter has run, the principal is available
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
boolean principalVisible = auth != null && auth.isAuthenticated();

Output:

directive                       after step   phase      principal?
------------------------------------------------------------------
addFilterBefore(., formLogin)   3            pre-auth   no
addFilterAfter(., httpBasic)    5            post-auth  yes
addFilterBefore(., authorize)   6            post-auth  yes
------------------------------------------------------------------
post-auth placements  : 2
pre-auth placements   : 1

A filter that needs the current user -- audit logging of who did what, per-tenant rate limiting keyed by account -- must be placed after authentication, or it will consistently see an anonymous request. This is a frequent source of "my filter says the user is null" confusion: the filter is correct, its position is wrong.

Real World Example: A Catch-All Chain That Shadows the Secured One

A team runs one application that serves a public marketing site and a protected admin console. They register two SecurityFilterChain beans. Selection between chains is not first-match-wins on the rules inside a chain -- it is first-matching-chain-wins across the beans, in @Order sequence. Each chain is scoped by a securityMatcher; the first chain whose matcher accepts the request handles it entirely, and no later chain is consulted. That single fact is what the two configurations below get right and wrong.

// Config A: the permissive chain matches everything and is ordered first
@Bean @Order(1)
SecurityFilterChain openFirst(HttpSecurity http) throws Exception {
    return http.securityMatcher("/**")            // matches ALL requests
        .authorizeHttpRequests(a -> a.anyRequest().permitAll())
        .build();
}
@Bean @Order(2)
SecurityFilterChain adminSecond(HttpSecurity http) throws Exception {
    return http.securityMatcher("/admin/**")      // never reached
        .authorizeHttpRequests(a -> a.anyRequest().hasRole("ADMIN"))
        .build();
}

// Config B: the specific chain is ordered first, catch-all second
@Bean @Order(1)
SecurityFilterChain adminFirst(HttpSecurity http) throws Exception {
    return http.securityMatcher("/admin/**")
        .authorizeHttpRequests(a -> a.anyRequest().hasRole("ADMIN"))
        .build();
}
@Bean @Order(2)
SecurityFilterChain openSecond(HttpSecurity http) throws Exception {
    return http.securityMatcher("/**")
        .authorizeHttpRequests(a -> a.anyRequest().permitAll())
        .build();
}

We send two requests -- /admin/users and /home -- through each configuration and record which chain's matcher claimed the request, the policy that chain applies, and whether /admin/users ended up guarded.

Output:

config  request         matched      policy          guarded
------------------------------------------------------------
A       /admin/users    /**          permitAll       no
A       /home           /**          permitAll       n/a
B       /admin/users    /admin/**    hasRole ADMIN   yes
B       /home           /**          permitAll       n/a
------------------------------------------------------------
config A admin guarded : no
config B admin guarded : yes
safe ordering          : B

In Config A the /** chain is ordered first, so /admin/users matches it and is served with permitAll -- the admin chain, however strict, is never consulted, exactly the airport lane whose broad sign claims every passenger before the strict lane can. Config B orders the specific /admin/** chain first, so admin traffic is caught by the strict chain and everything else falls through to the permissive one. The application starts cleanly and every page works in both configurations; nothing fails until an unauthenticated user opens the admin console in Config A and is let straight in.

The code shown carries a real design flaw beyond the ordering, and it is worth naming because it makes the ordering bug far more dangerous: the catch-all chain ends in anyRequest().permitAll() rather than anyRequest().authenticated(). Deny-by-default would have meant that even when the wrong chain claimed the request, the fallback was "blocked" rather than "wide open". By combining a permissive default with a /** matcher ordered ahead of the specific chain, the configuration turns a subtle ordering mistake into an open door. The fix is both to order specific chains before general ones and to make the default outcome a denial, so that a single mistake is not enough to expose a protected route.

Common Mistakes

  1. Ordering a broad rule or matcher before a specific one. Both authorizeHttpRequests rules and SecurityFilterChain beans are first-match-wins. A /** or /api/** entry placed above /admin/** claims the request first, and the stricter rule below it never runs. The application starts without error, so the gap is invisible until someone reaches the unprotected route.
  1. Omitting a deny-by-default final rule. Without anyRequest().authenticated() (or .denyAll()) at the end, any path you forget to list is simply unmatched and therefore open. A deny-by-default terminator makes a newly added, unlisted endpoint fail closed on the day it is merged.
  1. Expecting a security rejection to hit your controller advice. A 401 or 403 is produced inside the filter chain, before the DispatcherServlet selects a controller. Your @RestControllerAdvice never sees it unless you configure an AuthenticationEntryPoint or AccessDeniedHandler.
  1. Confusing 401 and 403. A 401 means "not authenticated -- start authenticating"; a 403 means "authenticated but not allowed". They come from different points, and treating them as interchangeable leads to login loops on 403 or silent access failures on 401.
  1. Placing a custom filter before authentication and then reading the principal. A filter added before the authentication filters runs while the request is anonymous, so SecurityContextHolder is empty. Audit or per-user filters must be inserted at or after the authentication filters.
  1. Assuming the security context propagates to other threads. The SecurityContextHolder is backed by a ThreadLocal. Work handed to an @Async method or a raw executor runs on a different thread with an empty context unless you propagate it deliberately.
  1. Leaving CSRF enabled on a stateless token API, or disabling it on a cookie-based app. CSRF protection matters when the browser sends credentials automatically via a cookie. A token API that carries its credential in a header does not need it; a session-cookie app very much does. Getting this backwards either breaks legitimate clients or opens a real hole.
  1. Registering two chains without a securityMatcher on the first. An unscoped first chain matches every request, so the second chain never runs. Each chain except the last must be scoped to the paths it owns.
  1. Treating a 403 as always an authorization problem. With CSRF protection on, an unsafe request missing a valid token is rejected by the CsrfFilter with a 403 long before the authorization filter is reached. Debugging the access rules for a request that never got there wastes time; check where the request short-circuited first.

Best Practices

  • Order authorization rules and filter chains from most specific to most general, and treat every /** entry as something that must sit last among its peers.
  • End every chain with an explicit deny-by-default rule -- anyRequest().authenticated() or .denyAll() -- so an unlisted path fails closed rather than open.
  • Scope each SecurityFilterChain with a securityMatcher (except the intentional catch-all placed last), and give the beans explicit @Order values so selection is deterministic.
  • Read the current user through @AuthenticationPrincipal or an injected Authentication rather than reaching into SecurityContextHolder from arbitrary code, keeping the dependency on the context explicit and testable.
  • Place custom filters relative to the authentication filters according to what they need: after them if they read the principal, before them only if they genuinely operate on anonymous requests.
  • Choose session-based or stateless authentication deliberately and configure consistently; do not issue cookies in a design you are treating as stateless.
  • Configure an AuthenticationEntryPoint and AccessDeniedHandler so 401 and 403 responses match your API's error format instead of the servlet container's default pages.
  • Propagate the security context explicitly when handing work to another thread, using Spring Security's context-propagating executors rather than assuming inheritance.

Practice Exercises

  1. Trace GET /reports for an anonymous user against a policy of requestMatchers('/reports').authenticated() and anyRequest().permitAll(). State which filter decides the outcome, which filter translates it, and the HTTP status returned.
  1. A configuration lists requestMatchers('/api/**').authenticated() above requestMatchers('/api/admin/**').hasRole('ADMIN') and omits anyRequest(). Name both defects and describe exactly what an ordinary logged-in non-admin user can reach.
  1. You add a filter that logs the acting user's name for every request, but it always logs "anonymous". Given addFilterBefore(auditFilter, UsernamePasswordAuthenticationFilter.class), explain why, and give the change that fixes it.
  1. Two POST requests to a CSRF-protected /orders both return 403: one carries a valid token from a non-admin user, the other carries no token. Identify which filter rejected each request and why sharing a status code makes this a debugging trap.