Video in progress
In Spring Security 6, how do you configure two different sets of security rules, one for the API and one for web pages?
You create a separate SecurityFilterChain bean for each, mark which paths it applies to with securityMatcher, and set the order with @Order. A request goes through the first matching chain, and the others don't run.
📖 Answer
A typical case: /api/** is stateless, with JWT, no CSRF; the rest of the pages use a session, form login and CSRF.
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
@Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**")
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(AbstractHttpConfigurer::disable)
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain web(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a
.requestMatchers("/", "/login", "/css/**").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}
}
Where people often go wrong:
securityMatcherandrequestMatchersare different things. The first decides which requests the chain takes, the second is the access rules inside the chain.- A chain without a matcher takes everything. It has to come last in the order, otherwise the chains after it never run.
- Error responses differ. For the API, a missing authentication is expected to give a 401 JSON; for the web, a redirect to the login page. That's why it's handy for each chain to have its own
authenticationEntryPoint. - For debugging, use
logging.level.org.springframework.security=TRACE: the log shows which chain was chosen and which filters ran.
Sign up to mark studied questions and save your progress.