Sub topic 3
Defining a SecurityFilterChain bean
This chapter assumes you can build REST controllers with Spring Boot, read Java lambdas, and write @Bean methods. It also assumes you know what the servlet filter chain is from the previous chapter. Here you will define the bean that configures that chain for a stateless API, and learn how its rules are evaluated.
What the bean does
Spring Security applies one or more SecurityFilterChain objects to incoming requests. Each chain holds an ordered list of servlet filters and a request matcher that decides which requests the chain handles. You build a chain with HttpSecurity, a builder that Spring injects into your @Bean method.
Older tutorials extend WebSecurityConfigurerAdapter. That class was deprecated in Spring Security 5.7 and removed in 6.0, which ships with Spring Boot 3. Declare a SecurityFilterChain bean instead. This is also how the examples below are written.
If you define no chain at all, Spring Boot's auto-configuration installs a default one. It requires authentication for every request, enables form login and HTTP Basic, and generates a random password at startup. As soon as you define your own SecurityFilterChain bean, the default backs off completely, so your chain must state everything you want.
A complete chain for a stateless API
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAnyRole("USER", "ADMIN")
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}Read the method from top to bottom. Each call on http configures one feature, and http.build() produces the immutable chain.
The lambda DSL
Every configurer takes a lambda, for example .csrf(csrf -> csrf.disable()). Spring Security 6 removed the older style that chained calls with .and(), so lambdas are the only form you will meet in current code. Use Customizer.withDefaults() when you want a feature switched on with its default settings, as with httpBasic above.
What each part does
| Call | Effect |
|---|---|
| `csrf(csrf -> csrf.disable())` | Turns off CSRF token checks. A later chapter explains when this is safe. |
| `sessionCreationPolicy(STATELESS)` | Stops Spring Security from creating or using an `HttpSession` to store the security context. |
| `authorizeHttpRequests(...)` | Declares which requests need which access. |
| `httpBasic(...)` | Reads credentials from the `Authorization: Basic ...` header. |
Because the policy is STATELESS, the client must send credentials on every request. HTTP Basic does this naturally. It is acceptable over HTTPS for simple internal APIs, but it sends the password with each call, which is one reason the JWT chapter exists.
How authorization rules are evaluated
The authorizeHttpRequests block is an ordered list. For each request, Spring Security tests the rules in the order you wrote them and applies the first one that matches. The rest are ignored.
That order sensitivity is the most common source of mistakes, so the diagram below shows the decision for one request.
Two practical consequences follow.
- Put specific rules before general ones. A rule such as
.anyRequest().authenticated()matches everything, so it must come last. Spring Security rejects a configuration where another rule followsanyRequest(). - End with a catch-all. If you list only the paths you remember, any path you forgot is left to the default, which may not be what you want.
anyRequest().authenticated()makes the safe choice the default. UsedenyAll()instead when you want unlisted paths blocked outright.
Roles and authorities
hasRole("ADMIN") checks for the authority ROLE_ADMIN. Spring adds the ROLE_ prefix for you, so do not write hasRole("ROLE_ADMIN"). Use hasAuthority("ROLE_ADMIN") if you want to spell the full name. For fine-grained permissions such as OAuth2 scopes, hasAuthority("SCOPE_orders.read") is the usual form.
Matching by method
requestMatchers(HttpMethod.GET, "/api/orders/**") restricts the rule to GET. A POST to the same path skips this rule and falls through to the next one that matches, here anyRequest().authenticated(). That means any logged-in user can POST to /api/orders. If that is not intended, add an explicit rule for the other methods.
Why unauthenticated and unauthorized requests differ
With the chain above, an anonymous call to a protected path gets 401 Unauthorized, because httpBasic supplies an entry point that sends a WWW-Authenticate: Basic challenge. An authenticated user who lacks the role gets 403 Forbidden. The names are historical: 401 means "who are you?" and 403 means "I know who you are, and the answer is no."
Testing that the chain loads
You can check the configuration quickly with a web slice test. @WebMvcTest does not pick up your @Configuration classes automatically, so import the one that holds the chain.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest
@Import(SecurityConfig.class)
class ChainSmokeTest {
@Autowired
MockMvc mvc;
@Test
void protectedPathRejectsAnonymous() throws Exception {
mvc.perform(get("/api/anything"))
.andExpect(status().isUnauthorized());
}
}This test needs the spring-boot-starter-test and spring-security-test dependencies. The full testing chapter covers mock users and JWTs.
Multiple chains
An application can declare several SecurityFilterChain beans. Each one starts with securityMatcher(...) to claim a set of paths, and @Order fixes which chain is consulted first. The first chain whose matcher accepts the request handles it, and later chains are never consulted for that request.
import org.springframework.core.annotation.Order;
@Bean
@Order(1)
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain defaultChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}The last chain should have no securityMatcher, so it catches everything the earlier ones did not. If two chains lack a matcher and share an order, startup fails or the wrong chain wins, so give each a distinct order.
Common errors
- Every request returns 401 after adding the bean. You replaced the default chain and forgot an authentication mechanism, or you have no user store. Add
httpBasicor a resource server, and define aUserDetailsService. - POST requests return 403 even with valid credentials. CSRF protection is still on. Disable it for a token-based stateless API, or send a CSRF token.
- A path you made public still requires login. An earlier rule matches it first. Reorder the rules.
hasRole("ROLE_ADMIN")never matches. The prefix is doubled. UsehasRole("ADMIN").@WebMvcTestreturns 401 for everything, or ignores your rules. The test did not load your configuration. Add@Import(SecurityConfig.class).- Compile error on
.and()orantMatchers. These come from the pre-6.0 API. Use lambdas andrequestMatchers.
Exercise
In the chain from this chapter, you add .requestMatchers("/api/**").authenticated() as the first rule in authorizeHttpRequests, before the /public/** rule. A client calls /api/admin/users as a user with only the USER role. What happens, and why?
Show answer
The request is allowed. The first matching rule wins, and /api/** matches /api/admin/users, so it only requires authentication. The hasRole("ADMIN") rule for /api/admin/** is never reached. Move the specific admin rule above the broad one.
Exercise
A POST to /api/orders succeeds for any authenticated user, although only GET is restricted to USER or ADMIN. Which rule handles the POST, and how would you restrict it?
Show answer
The POST skips the GET-only rule and is handled by anyRequest().authenticated(). Add a rule before the catch-all, for example .requestMatchers(HttpMethod.POST, "/api/orders/**").hasRole("USER"), or use hasAnyRole("USER", "ADMIN").