Sub topic 3
Defining a SecurityFilterChain bean
This chapter assumes you can build REST controllers with Spring Boot, read Java lambdas and annotations, and declare @Bean methods in a @Configuration class. You should also know HTTP methods, status codes and headers.
What the bean does
Spring Security applies a list of servlet filters to each request. A SecurityFilterChain bean describes one such list. You build it with HttpSecurity, a builder that adds, configures and orders filters for you. Since Spring Security 5.7 you declare the chain as a bean. The old WebSecurityConfigurerAdapter that you extended is removed in current versions.
When a request arrives, Spring Security picks the first chain whose request matcher fits. If you define one chain and give it no matcher, it handles every request.
A complete example
This configuration protects a stateless API with HTTP Basic.
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();
}
}Spring injects HttpSecurity into the method as a prototype-scoped bean. You configure it, then return http.build().
Reading the configuration
Each call takes a lambda that configures one feature. This is the lambda DSL, and it replaces the older .and() chaining.
csrf(csrf -> csrf.disable())turns off CSRF protection. A later chapter explains when that is safe. It is acceptable here because the API keeps no session cookie that a browser would send automatically.sessionManagement(...STATELESS)tells Spring Security not to create anHttpSessionand not to use one to store the security context. Each request must carry its own credentials.authorizeHttpRequests(...)lists the access rules.httpBasic(Customizer.withDefaults())enables HTTP Basic authentication with default settings.Customizer.withDefaults()means "turn this on and change nothing."
Rule order matters
Spring Security checks the rules from top to bottom and uses the first one that matches. Put specific rules before general ones. anyRequest() must come last, and Spring Security throws an error at startup if you add rules after it.
In the example, /public/** is open to everyone. A GET to /api/orders/42 needs the USER or ADMIN role. Anything under /api/admin/ needs ADMIN. Every other path needs a logged-in caller.
Note that hasRole("ADMIN") checks for the authority ROLE_ADMIN. Spring adds the ROLE_ prefix for you. If you write hasRole("ROLE_ADMIN"), startup fails with an error about the prefix.
Common errors
| Symptom | Likely cause |
|---|---|
| Every request returns 401 | No user is configured, or `anyRequest().authenticated()` covers a path you meant to open. |
| POST requests return 403 with a valid login | CSRF protection is still on. |
| A path you protected is open | A broader `permitAll()` rule appears earlier in the list. |
| Startup error after `anyRequest()` | You added a matcher after `anyRequest()`. |
Exercises
Exercise
A chain lists .anyRequest().authenticated() first and .requestMatchers("/public/**").permitAll() after it. What happens, and how do you fix it?
Show answer
Spring Security rejects the configuration at startup, because no rule may follow anyRequest(). Move the /public/** rule above anyRequest(). Rules are evaluated in order, so specific matchers come first.
Exercise
Which call makes the API reject a request that has no credentials, instead of reusing an earlier login stored in a session?
Show answer
sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)). It stops Spring Security from creating or using an HttpSession, so every request must authenticate itself.