Back to Spring Security: JWT, OAuth2, CSRF/CORS
Q5Question 5 of 11

SecurityFilterChain with Multiple Chains and @Order

Answer: SecurityFilterChain is a bean that defines a set of security filters and authorization rules for a specific group of HTTP requests, and Spring Security selects the first matching chain based on @Order and securityMatcher.

Key Concepts
  • SecurityFilterChain is a Spring bean that defines which security filters and authorization rules apply to matching HTTP requests.
  • You can define multiple SecurityFilterChain beans, each targeting different URL patterns using securityMatcher().
  • @Order controls which chain is evaluated first; the first chain whose matcher matches handles the request.
  • securityMatcher() decides if the entire chain applies; requestMatchers() defines authorization rules within the selected chain.
  • Each chain can have completely independent authentication mechanisms: JWT for APIs, form login for admin, permitAll for public.
  • FilterChainProxy iterates through all SecurityFilterChain beans in order and delegates to the first match.

Definition

SecurityFilterChain is a bean that defines a set of security filters and authorization rules for a specific group of HTTP requests, and Spring Security selects the first matching chain based on @Order and securityMatcher.
  • SecurityFilterChain – an interface with two methods: matches(HttpServletRequest) to check if this chain handles the request, and getFilters() to return the list of security filters.
  • FilterChainProxy – the master filter that holds all SecurityFilterChain beans and delegates each request to the first matching chain.
  • securityMatcher() – a method on HttpSecurity that sets which URL patterns this chain handles; if omitted, the chain matches all requests.
  • @Order – controls evaluation priority; lower numbers are evaluated first.
  • requestMatchers() – defines fine-grained authorization rules within a chain (permit, deny, require role).

Think of a bank building with multiple security checkpoints. The main entrance has a guard (FilterChainProxy) who checks your destination. If you are heading to the ATM lobby, you go through checkpoint 1 (API chain). If you are heading to the vault, you go through checkpoint 2 (admin chain). Each checkpoint has its own rules: the ATM lobby checks your card (JWT), the vault checks your ID badge and PIN (form login). The guard always sends you to the first matching checkpoint.

Understanding the Concepts

What is SecurityFilterChain?

SecurityFilterChain is an interface in Spring Security that pairs a request matcher with a list of security filters. When an HTTP request arrives, Spring Security's FilterChainProxy iterates through all registered SecurityFilterChain beans and uses the first one whose matcher returns true.

The interface has two methods:

JAVA
public interface SecurityFilterChain {
    boolean matches(HttpServletRequest request);
    List<Filter> getFilters();
}

In practice, you never implement this interface directly. You create SecurityFilterChain beans using the HttpSecurity builder.

JAVA
package com.bank.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class BankSecurityConfig {

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

How does FilterChainProxy select the right chain?

FilterChainProxy is the servlet filter that bridges the servlet container to Spring Security. It holds an ordered list of SecurityFilterChain beans.

For each incoming request, FilterChainProxy:

  1. Iterates through the list in @Order sequence.
  2. Calls matches(request) on each chain.
  3. Uses the first chain that returns true.
  4. Passes the request through that chain's filters.
  5. Ignores all remaining chains.

This means the order and the matcher are critical. A chain without a securityMatcher() matches every request, so it should always be last.

How do you configure multiple chains for a banking application?

A real banking application has different security needs for different endpoints. The mobile banking API uses JWT. The internal operations portal uses form login with sessions. The health check endpoint is public.

JAVA
package com.bank.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class BankMultiChainConfig {

    @Bean
    @Order(1)
    SecurityFilterChain healthChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/actuator/health", "/api/status")
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/api/**")
            .csrf(csrf -> csrf.disable())
            .sessionManagement(sess -> sess
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/accounts/**").hasAuthority("SCOPE_accounts.read")
                .requestMatchers("/api/transfers/**").hasAuthority("SCOPE_transfers.write")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .build();
    }

    @Bean
    @Order(3)
    SecurityFilterChain adminChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/admin/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/login").permitAll()
                .anyRequest().hasRole("BANK_ADMIN")
            )
            .formLogin(form -> form
                .loginPage("/admin/login")
                .defaultSuccessUrl("/admin/dashboard")
            )
            .build();
    }
}

A request to /api/accounts/SAV2001 skips chain 1 (does not match /actuator/health), matches chain 2 (/api/**), and is processed with JWT validation.

A request to /admin/dashboard skips chains 1 and 2, matches chain 3, and requires form login.

What happens if you forget securityMatcher?

If a chain has no securityMatcher(), it matches every request. If this chain has a low @Order, it will capture all requests and the other chains will never be used.

JAVA
// WRONG: This chain has no securityMatcher and @Order(1)
// It captures ALL requests, including /admin/**
@Bean
@Order(1)
SecurityFilterChain brokenChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .anyRequest().authenticated()
        )
        .httpBasic(Customizer.withDefaults())
        .build();
}

// This chain is NEVER reached because brokenChain matches everything
@Bean
@Order(2)
SecurityFilterChain adminChain(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/admin/**")
        .authorizeHttpRequests(auth -> auth
            .anyRequest().hasRole("ADMIN")
        )
        .formLogin(Customizer.withDefaults())
        .build();
}

The fix is to always add securityMatcher() to specific chains, or put the catch-all chain last with the highest @Order.

What filters does a SecurityFilterChain contain?

Each chain contains a list of security filters. The exact filters depend on your configuration. Common filters include:

FilterPurpose
SecurityContextPersistenceFilterLoads/saves the SecurityContext between requests
CsrfFilterValidates CSRF tokens for state-changing requests
UsernamePasswordAuthenticationFilterProcesses form login submissions
BearerTokenAuthenticationFilterExtracts and validates JWT bearer tokens
AuthorizationFilterEvaluates authorization rules (permit, deny, role check)
ExceptionTranslationFilterConverts security exceptions to HTTP 401/403 responses

You can see the full list of filters for each chain by enabling debug logging:

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

How do you debug which chain handled a request?

Add this to your application.properties:

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

The log output shows:

TEXT
Securing GET /api/accounts/SAV2001
This request matched securityMatcher: /api/**
Security filter chain: [DisableEncodeUrlFilter, ..., AuthorizationFilter]

In production, reduce the log level to WARN or ERROR. Debug-level security logging is verbose and may expose sensitive information.

What are common mistakes when configuring multiple chains?

The most frequent mistakes with multiple SecurityFilterChain beans:

1. Overlapping matchers without distinct @Order: Two chains matching /api/** with the same order leads to unpredictable behavior.

JAVA
// WRONG: Both chains match /api/** with no clear priority
@Bean
SecurityFilterChain chainA(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/api/**")
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults())
        .build();
}

@Bean
SecurityFilterChain chainB(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/api/**")
        .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
        .build();
}

// CORRECT: Use @Order to define priority
@Bean
@Order(1)
SecurityFilterChain chainA(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/api/admin/**")  // More specific pattern
        .authorizeHttpRequests(auth -> auth.anyRequest().hasRole("ADMIN"))
        .build();
}

@Bean
@Order(2)
SecurityFilterChain chainB(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/api/**")  // Broader pattern
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .build();
}

2. Disabling CSRF on the wrong chain: CSRF should be disabled only on stateless JWT chains. Disabling it on a session-based chain exposes it to CSRF attacks.

3. Forgetting to configure exception handling per chain: Each chain can have its own AuthenticationEntryPoint and AccessDeniedHandler. The API chain should return JSON errors; the admin chain should redirect to a login page.

What should a senior engineer know?

  • Spring Boot's auto-configured SecurityFilterChain backs off when you define your own bean. If you define only one chain for /api/**, other URLs may have no security at all. Always define a catch-all chain.
  • In production, use @ConditionalOnProperty to conditionally enable debug or actuator security chains based on environment variables.
  • Each SecurityFilterChain has its own independent set of filters. A CORS configuration on one chain does not apply to another chain.
  • The DefaultSecurityFilterChain class is the standard implementation created by http.build(). It stores the request matcher and the filter list.

What are common interview follow-up questions?

  • What happens if two chains match the same URL? Only the first chain (by @Order) handles the request.
  • Can a request fall through all chains? If no chain matches, Spring Security's default behavior depends on the auto-configuration. In Spring Boot, the default chain matches all requests.
  • Can you add a custom filter to only one chain? Yes. Call http.addFilterBefore() or http.addFilterAfter() inside that specific chain's configuration.
  • Is the order of requestMatchers within a chain important? Yes. Spring Security evaluates matchers in declaration order and uses the first match.

Visual Overview

DIAGRAM
┌───────────────────────────────────────────┐
│          Incoming HTTP Request             │
│     GET /api/accounts/SAV2001              │
└──────────────────┬────────────────────────┘
                   │
                   ▼
┌───────────────────────────────────────────┐
│           FilterChainProxy                │
│  Iterates SecurityFilterChain beans       │
└──────────────────┬────────────────────────┘
                   │
    ┌──────────────┼──────────────────────┐
    ▼              ▼                      ▼
┌─────────┐  ┌──────────┐         ┌──────────┐
│@Order(1)│  │ @Order(2)│         │ @Order(3)│
│/actuator│  │ /api/**  │         │ /admin/**│
│  MATCH? │  │  MATCH?  │         │  MATCH?  │
│   NO    │  │   YES    │         │ SKIPPED  │
└─────────┘  └────┬─────┘         └──────────┘
                  │
                  ▼
         ┌─────────────────┐
         │ Apply filters:  │
         │ CSRF disabled   │
         │ JWT validation  │
         │ Authorization   │
         └────────┬────────┘
                  │
                  ▼
         ┌─────────────────┐
         │  Controller      │
         │  AccountController│
         └─────────────────┘

Key Takeaway

SecurityFilterChain is the central building block of Spring Security configuration in modern Spring Boot applications. Instead of a single monolithic security class, you define one or more SecurityFilterChain beans, each responsible for a specific group of URLs.

FilterChainProxy is the master filter that holds all your SecurityFilterChain beans in a list ordered by @Order. When an HTTP request arrives, it walks through the list and hands the request to the first chain whose securityMatcher matches the URL. Once a chain is selected, the request passes through that chain's filters: CSRF checks, authentication, authorization, and exception handling. All other chains are ignored for that request.

In a banking application, Rajesh would define three chains: a public health check chain, a JWT-secured API chain for the mobile banking app, and a form-login chain for the internal admin portal. Each chain is independent. The API chain disables CSRF and sessions because it uses bearer tokens. The admin chain keeps CSRF enabled and uses session cookies. They never interfere with each other.

The key distinction that interviewers test is securityMatcher versus requestMatchers. The securityMatcher on HttpSecurity decides whether the entire chain handles the request. The requestMatchers inside authorizeHttpRequests define which specific URLs need which permissions within that chain. Confusing the two is one of the most common mistakes in Spring Security configuration.

The one sentence to remember: SecurityFilterChain is a bean that pairs a URL matcher with a list of security filters, and FilterChainProxy always uses the first matching chain by @Order.

---

Share
Use ← → arrow keys to navigate