Back to Spring Security: JWT, OAuth2, CSRF/CORS
Q4Question 4 of 11

SecurityFilterChain vs WebSecurityConfigurerAdapter

Answer: WebSecurityConfigurerAdapter was the old inheritance-based way to configure Spring Security; SecurityFilterChain is the modern bean-based replacement that was introduced in Spring Security 5.2 and became mandatory in Spring Security 6.

Key Concepts
  • WebSecurityConfigurerAdapter was the traditional way to configure Spring Security by extending a class and overriding methods.
  • It was deprecated in Spring Security 5.7 and removed in Spring Security 6 because bean-based configuration is cleaner and more composable.
  • SecurityFilterChain is a bean you define using a @Bean method that receives HttpSecurity and returns a filter chain.
  • The bean approach supports multiple independent filter chains with @Order, each matching different URL patterns.
  • Modern Spring Boot 3+ and Spring Security 6+ projects must use SecurityFilterChain because the adapter class no longer exists.
  • Migration requires replacing configure(HttpSecurity) overrides with @Bean SecurityFilterChain methods and authorizeRequests with authorizeHttpRequests.

Definition

WebSecurityConfigurerAdapter was the old inheritance-based way to configure Spring Security; SecurityFilterChain is the modern bean-based replacement that was introduced in Spring Security 5.2 and became mandatory in Spring Security 6.
  • WebSecurityConfigurerAdapter – an abstract class you extended and overrode configure(HttpSecurity) to set up security rules; removed in Spring Security 6.
  • SecurityFilterChain – a bean returned from a @Bean method that defines which security filters apply to which HTTP requests.
  • Why the change – bean-based configuration is easier to compose, test, and understand than deep inheritance hierarchies.
  • @Order – when you define multiple SecurityFilterChain beans, @Order controls which chain is evaluated first.
  • authorizeHttpRequests – the modern replacement for authorizeRequests, providing better performance and a cleaner authorization model.

Think of the old adapter approach like a bank branch where one single manager (the adapter) controlled every security decision by overriding a rulebook. The new SecurityFilterChain approach is like having separate, independent security desks: one for the ATM lobby, one for the vault area, one for the public counter. Each desk has its own clear rules, and the bank can add or remove a desk without rewriting the entire security manual.

Understanding the Concepts

What was WebSecurityConfigurerAdapter?

WebSecurityConfigurerAdapter was an abstract class in Spring Security that provided default security configuration. You extended it and overrode methods like configure(HttpSecurity http) to customize authentication and authorization rules.

This was the standard approach in Spring Security 4.x and 5.x projects.

JAVA
package com.bank.config;

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.annotation.web.configuration.WebSecurityConfigurerAdapter;

// OLD approach: Spring Security 5.6 and earlier
@Configuration
@EnableWebSecurity
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/public/**").permitAll()
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

The problem with this approach was that it relied on inheritance. You could only extend one adapter, making it difficult to define separate security rules for different URL patterns.

What is SecurityFilterChain?

SecurityFilterChain is a bean-based approach introduced in Spring Security 5.2. Instead of extending a class, you define a @Bean method that receives HttpSecurity, configures it, and returns a SecurityFilterChain.

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;

// MODERN approach: Spring Security 6+ / Spring Boot 3+
@Configuration
@EnableWebSecurity
public class BankSecurityConfig {

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

This is cleaner because each @Bean method is an independent unit. You can define as many filter chains as you need.

Why was WebSecurityConfigurerAdapter removed?

Spring Security 5.7 deprecated the adapter. Spring Security 6.0 removed it entirely. The reasons are:

  • Inheritance is rigid – you can only extend one class, so having multiple security configurations required awkward inner classes.
  • Bean-based is composable – each SecurityFilterChain bean is independent. You can split API security and web security into separate beans.
  • Testing is easier – beans can be mocked, replaced, or conditionally loaded using @Profile or @ConditionalOnProperty.
  • Lambda DSL is cleaner – the new style uses lambda expressions instead of .and() chaining, which was error-prone.

How do you define multiple SecurityFilterChain beans?

When your application has different security requirements for different endpoints (for example, a stateless JWT API and a session-based admin panel), you define multiple beans with @Order.

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 BankMultiSecurityConfig {

    // Chain 1: Stateless JWT for API endpoints
    @Bean
    @Order(1)
    SecurityFilterChain apiSecurityChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/api/**")
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/accounts/**").hasAuthority("SCOPE_accounts.read")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .build();
    }

    // Chain 2: Session-based for admin portal
    @Bean
    @Order(2)
    SecurityFilterChain adminSecurityChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/admin/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/login").permitAll()
                .anyRequest().hasRole("ADMIN")
            )
            .formLogin(form -> form
                .loginPage("/admin/login")
                .defaultSuccessUrl("/admin/dashboard")
            )
            .build();
    }
}

Spring Security evaluates chains in @Order sequence. The first chain whose securityMatcher() matches the request URL handles the request. The remaining chains are skipped.

What is the difference between securityMatcher and requestMatchers?

This is a common interview trap. They serve different purposes:

AspectsecurityMatcher()requestMatchers()
PurposeDecides whether this entire SecurityFilterChain handles the requestDefines authorization rules within a selected chain
ScopeChain-level: selects which chain processes the requestRule-level: matches specific endpoints for permit/deny decisions
Example.securityMatcher("/api/**").requestMatchers("/api/admin/**").hasRole("ADMIN")
What happens if missingThe chain matches all requestsNo authorization rule is applied for those URLs

A request to /api/accounts/SAV2001 first matches the chain with securityMatcher("/api/"). Inside that chain, requestMatchers("/api/accounts/") decides the authorization rule.

How do you migrate from the old style to the new style?

Here is a side-by-side migration reference:

Old (Spring Security 5.x)New (Spring Security 6+)
extends WebSecurityConfigurerAdapterRemove the extends, use @Configuration + @EnableWebSecurity
configure(HttpSecurity http)@Bean SecurityFilterChain filterChain(HttpSecurity http)
.authorizeRequests().authorizeHttpRequests()
.antMatchers("/path").requestMatchers("/path")
.and().httpBasic().httpBasic(Customizer.withDefaults())
configure(AuthenticationManagerBuilder)Define UserDetailsService and PasswordEncoder as beans
JAVA
// OLD: AuthenticationManagerBuilder approach
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder);
}

// NEW: Bean-based approach
@Bean
UserDetailsService userDetailsService() {
    return new BankUserDetailsService(userRepository);
}

@Bean
PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
}

What are common migration mistakes?

The most frequent mistake is mixing old and new APIs:

JAVA
// WRONG: Using authorizeRequests (old) with SecurityFilterChain (new)
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .authorizeRequests()  // Compilation error in Spring Security 6
            .antMatchers("/api/**").authenticated()
        .and()
        .build();
}

// CORRECT: Using authorizeHttpRequests (new) with SecurityFilterChain (new)
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/**").authenticated()
        )
        .build();
}

Another mistake is forgetting securityMatcher() when defining multiple chains. Without it, the first chain matches all requests and the second chain is never used.

What should a senior engineer know?

  • The FilterChainProxy inside Spring Security holds a list of SecurityFilterChain beans. For each incoming request, it iterates the list and uses the first chain whose matcher returns true.
  • In Spring Boot 3, the default auto-configuration creates one SecurityFilterChain bean. If you define your own, the auto-configured one backs off.
  • You can use @ConditionalOnProperty to conditionally enable or disable a security chain in different environments.
  • When debugging, set logging.level.org.springframework.security=DEBUG to see which chain handled each request and which filters were applied.

What are common interview follow-up questions?

  • Can you have more than two SecurityFilterChain beans? Yes, as many as needed, each with a unique @Order.
  • What happens if two chains have the same @Order? The behavior is undefined and depends on bean registration order. Always use distinct order values.
  • Does removing the adapter change how filters work internally? No. The filter chain mechanism is the same. Only the configuration API changed.
  • Can you still use XML configuration? Yes, but it is rare in modern Spring Boot projects.

Visual Overview

DIAGRAM
┌─────────────────────────────────────────────────┐
│              HTTP Request Arrives                │
└──────────────────────┬──────────────────────────┘
                       │
                       ▼
┌─────────────────────────────────────────────────┐
│             FilterChainProxy                    │
│  (holds all SecurityFilterChain beans)          │
└──────────────────────┬──────────────────────────┘
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
   ┌────────────┐ ┌────────────┐ ┌────────────┐
   │ @Order(1)  │ │ @Order(2)  │ │ @Order(3)  │
   │ /api/**    │ │ /admin/**  │ │ /**        │
   │ JWT+Stateless│ │ Form Login │ │ Default   │
   └─────┬──────┘ └────────────┘ └────────────┘
         │
         ▼
   First matching chain handles the request.
   Other chains are skipped entirely.

Key Takeaway

In older Spring Security projects, you configured security by extending WebSecurityConfigurerAdapter and overriding its configure methods. This approach worked but was rigid. You could only extend one class, and having separate security rules for API endpoints and admin pages meant creating awkward inner static classes.

Spring Security 5.2 introduced the SecurityFilterChain bean as an alternative. Instead of inheritance, you define one or more @Bean methods that each receive HttpSecurity, configure it, and return a SecurityFilterChain. Each bean can target a different set of URLs using securityMatcher and have completely independent security rules: one chain for JWT-secured APIs, another for session-based admin pages, another for public health-check endpoints.

In a banking application at National Bank of India, Rajesh would define an API chain that disables CSRF and uses stateless JWT validation for the mobile banking API, and a separate chain with form login and CSRF protection for the internal operations portal. Each chain is a self-contained unit that is easy to read, test, and maintain.

Spring Security 5.7 deprecated the adapter, and Spring Security 6.0 removed it entirely. If you are using Spring Boot 3 or later, SecurityFilterChain is the only option. Migration involves replacing authorizeRequests with authorizeHttpRequests, antMatchers with requestMatchers, and moving UserDetailsService and PasswordEncoder to standalone beans.

The one sentence to remember: SecurityFilterChain replaced WebSecurityConfigurerAdapter because bean-based configuration is composable, testable, and supports multiple independent security chains without inheritance.

---

Share
Use ← → arrow keys to navigate