Configuring SecurityFilterChain

Spring Security · lesson 3 of 31 · 4 min read

Write the modern lambda-DSL config bean and order request rules so they actually take effect.

Open this lesson in the learning hub

Key points

  • WebSecurityConfigurerAdapter was removed in Spring Security 6. Expose a SecurityFilterChain bean instead.
  • Spring Security 6 uses the lambda DSL. The old .and() chaining is deprecated and gone in 7.
  • Rules match top to bottom, first match wins. A broad pattern above a narrow one silently swallows it.
  • Finish with anyRequest().authenticated() so every new endpoint is locked until you say otherwise.
  • Different rules for API and UI? Declare several chains, each with a securityMatcher, ordered with @Order.

Example

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/api/**")                 // this chain only handles /api
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/posts/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())          // deny by default
            .csrf(csrf -> csrf.disable())               // token API, no cookies
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .httpBasic(Customizer.withDefaults())
            .build();
    }
}

One bean, one chain, rules from most specific to "anyRequest().authenticated()".

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.