SecurityFilterChain Configuration in Spring Security
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.
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.
| Method | Configures | Typical use |
|---|---|---|
securityMatcher(...) | Which requests this chain handles | "/api/**" for an API chain |
authorizeHttpRequests(...) | URL authorization rules | requestMatchers("/admin/**").hasRole("ADMIN") |
httpBasic(...) | HTTP Basic authentication | Scripts, internal tools, simple APIs |
formLogin(...) | Login form and redirects | Browser applications |
oauth2ResourceServer(...) | Bearer token (JWT) validation | APIs behind an identity provider |
sessionManagement(...) | Session creation and fixation | STATELESS for token or Basic APIs |
csrf(...) | CSRF token checks | Keep on for cookie-based browsers |
cors(...) | Cross-origin rules | Single-page apps on another origin |
headers(...) | Security response headers | Content Security Policy, frame options |
exceptionHandling(...) | Entry point and access-denied handler | Custom JSON 401 and 403 bodies |
addFilterBefore(...) | Your own filter at a position | API key or tenant checks |
The general shape of every chain bean is the same:
@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());
}
}
package com.javabytechie.clinic;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClinicController {
@GetMapping("/api/clinics")
public List<String> clinics() {
return List.of("Koramangala", "Whitefield");
}
@GetMapping("/api/appointments")
public List<Map<String, String>> myAppointments(Principal principal) {
return List.of(Map.of("patient", principal.getName(), "slot", "2026-11-21T10:30", "doctor", "dr-rao"));
}
@GetMapping("/api/admin/reports")
public Map<String, Integer> reports() {
return Map.of("appointmentsToday", 42);
}
@GetMapping("/staff/dashboard")
public String dashboard(Principal principal) {
return "Welcome, " + principal.getName() + ". 42 appointments today.";
}
}
package com.javabytechie.clinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ClinicApplication {
public static void main(String[] args) {
SpringApplication.run(ClinicApplication.class, args);
}
}
6. Step-by-Step Code Explanation
@Order(1)andsecurityMatcher("/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.- Rule order inside the chain. The public
GET /api/clinicsrule and the admin rule come beforeanyRequest(). Spring Security even rejects a configuration that putsanyRequest()before other rules, because the later rules could never match. STATELESSsessions. 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.- 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.
- 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:
$ 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
| Advantages | Limitations |
|---|---|
| Plain beans: no inheritance, easy to split by feature or module | Several chains need careful ordering and matchers |
| The lambda DSL keeps each feature's settings together | Rules are order-sensitive; a broad rule placed early hides the specific ones after it |
| Different areas can use different login mechanisms | A request handled by one chain gets nothing from another chain's configuration |
| Spring Boot's default backs off cleanly once you declare a chain | Forgetting 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 withanyRequest().authenticated()ordenyAll()so new endpoints are protected by default. - Using
web.ignoring()for public pages. AWebSecurityCustomizerthat ignores paths removes all protection, including security headers. PreferpermitAll(), 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
hasRoleand authority names.hasRole("ADMIN")checksROLE_ADMIN; see role vs authority.
10. Summary
- A
SecurityFilterChainbean built fromHttpSecurityreplaces the removedWebSecurityConfigurerAdapter. - Declaring your own chain switches off Spring Boot's default chain.
- With several chains, order them with
@Orderand scope all but the last withsecurityMatcher. - 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
Frequently Asked Questions (FAQ)
Q1. What replaced WebSecurityConfigurerAdapter in Spring Security?
A @Bean method that returns a SecurityFilterChain built from HttpSecurity. The adapter was deprecated in Spring Security 5.7 and removed in 6.0.
Q2. How does Spring Security choose between multiple SecurityFilterChain beans?
It sorts them by @Order and uses the first chain whose securityMatcher matches the request. Only that chain's filters run for the request.
Q3. What is the difference between securityMatcher and requestMatchers?
securityMatcher decides whether the whole chain handles a request. requestMatchers inside authorizeHttpRequests selects which authorization rule applies within a chain that has already been chosen.
Q4. Should I use web.ignoring() or permitAll() for public URLs?
Use permitAll(). Ignored paths skip the entire security filter chain, so they lose security headers and other protections. permitAll() keeps the chain but allows everyone through.
Q5. Why does Spring Boot stop creating the default user and login when I add a SecurityFilterChain?
Spring Boot's security auto-configuration backs off when it finds your own SecurityFilterChain bean. The generated user backs off separately when you define a UserDetailsService or similar bean.