00:00

SecurityFilterChain Configuration in Spring Security

Last updated:

A SecurityFilterChain bean is how you configure Spring Security in a modern Spring Boot application. It states which requests it covers, which login mechanisms apply, which URL rules must pass and which protections to adjust. Spring Security turns that description into the ordered filter list that guards every request.

This tutorial shows how to write that configuration with the HttpSecurity lambda DSL, how rule order affects the result, and how to give two parts of one application, a mobile API and a staff website, completely different security with two chains.

1. What Is SecurityFilterChain Configuration?

SecurityFilterChain is an interface with two responsibilities: deciding whether it applies to a request (matches) and supplying the filters to run (getFilters). You rarely implement it directly. Instead, you declare a @Bean method that receives an HttpSecurity builder, configure it, and return http.build().

This bean-based style replaced WebSecurityConfigurerAdapter, which was deprecated in Spring Security 5.7 and removed in 6.0. If you meet old code that extends the adapter and overrides configure(HttpSecurity), the body of that method moves almost unchanged into a SecurityFilterChain bean. How the chain runs at request time is explained in Spring Security filter chain.

2. Why Configure Your Own SecurityFilterChain?

Spring Boot provides a default chain that requires login for everything and enables form login and HTTP Basic. That default is safe but rarely what an application needs: public pages must be opened, admin areas restricted, APIs made stateless, and login pages customised.

As soon as you declare your own SecurityFilterChain bean, Spring Boot's default chain backs off completely. From then on, your bean is the single, readable source of truth for web security, which also makes it the first place to look during a security review.

3. How Spring Security Selects and Applies a Chain

An application can declare several chains. FilterChainProxy checks them in order and uses the first one whose securityMatcher matches the request. Inside the chosen chain, authorizeHttpRequests rules are also checked from top to bottom, and the first rule that matches decides.

Choosing between two security filter chainsRequests under /api/** are handled by the API chain with HTTP Basic and no sessions. All other requests fall through to the web chain with form login. Incoming request FilterChainProxy tries chains in order @Order(1) apiChain: /api/** HTTP Basic, STATELESS sessions, CSRF off for a non-browser client @Order(2) webChain: everything else form login, sessions, CSRF on, staff pages need ROLE_STAFF matches otherwise
Figure 1: the first matching chain wins, so the narrow /api/** chain is ordered before the catch-all web chain.

4. Important HttpSecurity Methods

Each method takes a lambda (a Customizer) that configures one feature. Pass Customizer.withDefaults() to accept the defaults, or call disable() to remove a feature.

MethodConfiguresTypical use
securityMatcher(...)Which requests this chain handles"/api/**" for an API chain
authorizeHttpRequests(...)URL authorization rulesrequestMatchers("/admin/**").hasRole("ADMIN")
httpBasic(...)HTTP Basic authenticationScripts, internal tools, simple APIs
formLogin(...)Login form and redirectsBrowser applications
oauth2ResourceServer(...)Bearer token (JWT) validationAPIs behind an identity provider
sessionManagement(...)Session creation and fixationSTATELESS for token or Basic APIs
csrf(...)CSRF token checksKeep on for cookie-based browsers
cors(...)Cross-origin rulesSingle-page apps on another origin
headers(...)Security response headersContent Security Policy, frame options
exceptionHandling(...)Entry point and access-denied handlerCustom JSON 401 and 403 bodies
addFilterBefore(...)Your own filter at a positionAPI key or tenant checks

The general shape of every chain bean is the same:

Syntax
@Bean
SecurityFilterChain someChain(HttpSecurity http) throws Exception {
    http
        .securityMatcher("/area/**")                    // optional: which requests
        .authorizeHttpRequests(auth -> auth             // who may access what
            .requestMatchers("/area/public/**").permitAll()
            .anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults());          // how users log in
    return http.build();
}

5. A Complete Example: Clinic API and Staff Website

A clinic runs one Spring Boot application with two kinds of clients. A patient mobile app calls /api/** and sends HTTP Basic credentials on every call. Staff use a browser and sign in through a form to reach /staff/**. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.clinic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    // Chain 1: the patient mobile API
    @Bean
    @Order(1)
    SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/clinics").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults())
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // The mobile app sends credentials itself and never uses browser cookies
            .csrf(csrf -> csrf.disable());
        return http.build();
    }

    // Chain 2: the staff website (every request not matched above)
    @Bean
    @Order(2)
    SecurityFilterChain webChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/error").permitAll()
                .requestMatchers("/staff/**").hasRole("STAFF")
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
            .logout(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        // Demo users only; load real users from a database
        return new InMemoryUserDetailsManager(
            User.withUsername("kiran").password(encoder.encode("kiran-pass")).roles("PATIENT").build(),
            User.withUsername("dr-rao").password(encoder.encode("rao-pass")).roles("STAFF").build());
    }
}

6. Step-by-Step Code Explanation

  1. @Order(1) and securityMatcher("/api/**"). The API chain is tried first and only claims API paths. Without a matcher it would claim every request, and the web chain would never run.
  2. Rule order inside the chain. The public GET /api/clinics rule and the admin rule come before anyRequest(). Spring Security even rejects a configuration that puts anyRequest() before other rules, because the later rules could never match.
  3. STATELESS sessions. The API never creates an HTTP session, so each call must carry its own credentials. This suits mobile clients and avoids session state on the server.
  4. CSRF disabled only for the API. CSRF attacks rely on a browser attaching stored credentials automatically. The mobile app adds credentials to each call itself, so the token check adds nothing there. The staff website keeps CSRF protection because it uses a session cookie.
  5. The web chain has no matcher. It is the catch-all. It also permits /error, the path Spring Boot forwards to when any request fails, including failed API requests.

7. Expected Output

Running the application and calling both areas gave the following results:

Terminal
$ curl localhost:8080/api/clinics
HTTP/1.1 200
["Koramangala","Whitefield"]

$ curl localhost:8080/api/appointments
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
{"timestamp":"2026-11-18T12:15:01.276Z","status":401,"error":"Unauthorized","path":"/api/appointments"}

$ curl -u kiran:kiran-pass localhost:8080/api/appointments
HTTP/1.1 200
[{"patient":"kiran","slot":"2026-11-21T10:30","doctor":"dr-rao"}]

$ curl -u kiran:kiran-pass localhost:8080/api/admin/reports
HTTP/1.1 403
{"timestamp":"2026-11-18T12:15:01.478Z","status":403,"error":"Forbidden","path":"/api/admin/reports"}

$ curl localhost:8080/staff/dashboard
HTTP/1.1 302
Location: http://localhost:8080/login

$ curl -u dr-rao:rao-pass localhost:8080/staff/dashboard
HTTP/1.1 302
Location: http://localhost:8080/login

The two chains behave differently for the same kind of request. An unauthenticated API call receives a 401 with a Basic challenge, while an unauthenticated staff page receives a 302 redirect to the login form. Kiran's successful API call returns no Set-Cookie header, which proves that the stateless setting works. The last request is the most instructive: Dr. Rao sends valid Basic credentials to a staff page, but the web chain has no httpBasic(), so the header is ignored and the browser-style redirect to /login happens anyway.

8. Advantages and Limitations

AdvantagesLimitations
Plain beans: no inheritance, easy to split by feature or moduleSeveral chains need careful ordering and matchers
The lambda DSL keeps each feature's settings togetherRules are order-sensitive; a broad rule placed early hides the specific ones after it
Different areas can use different login mechanismsA request handled by one chain gets nothing from another chain's configuration
Spring Boot's default backs off cleanly once you declare a chainForgetting a rule now means relying on your own anyRequest() fallback

9. Common Mistakes and Best Practices

  • Two chains without matchers. Both match every request; only the first one ever runs. Give every chain except the last a securityMatcher.
  • Ending without anyRequest(). Finish every chain with anyRequest().authenticated() or denyAll() so new endpoints are protected by default.
  • Using web.ignoring() for public pages. A WebSecurityCustomizer that ignores paths removes all protection, including security headers. Prefer permitAll(), which still runs the chain.
  • Disabling CSRF everywhere. Disable it only for chains whose clients never authenticate with browser-managed cookies or cached Basic credentials.
  • Mixing hasRole and authority names. hasRole("ADMIN") checks ROLE_ADMIN; see role vs authority.

10. Summary

  • A SecurityFilterChain bean built from HttpSecurity replaces the removed WebSecurityConfigurerAdapter.
  • Declaring your own chain switches off Spring Boot's default chain.
  • With several chains, order them with @Order and scope all but the last with securityMatcher.
  • Inside a chain, authorization rules are checked top to bottom, so specific rules come first and anyRequest() comes last.
  • Session, CSRF and login settings are per chain, so an API and a website can be configured independently.

11. References