The SecurityFilterChain Bean

Your First Configuration

As soon as you declare a SecurityFilterChain bean, Spring Boot's default chain backs off and your rules apply. Each method on HttpSecurity takes a lambda (the "lambda DSL") that configures one feature:

package com.shopease.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth          // 1. who may access what
                .requestMatchers("/", "/api/products/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())        // 2. login page for browsers
            .httpBasic(Customizer.withDefaults());       // 3. Basic auth for API clients
        return http.build();
    }
}

Old Style vs Lambda DSL

Before (Spring Security 5, removed)Now (Spring Security 6)
extends WebSecurityConfigurerAdapter@Bean SecurityFilterChain
.authorizeRequests().authorizeHttpRequests(auth -> ...)
.antMatchers("/api/**").requestMatchers("/api/**")
.and() chainingone lambda per feature, no and()
.csrf().disable().csrf(csrf -> csrf.disable())

Note: Many blog posts and Stack Overflow answers still show the old style. If you see WebSecurityConfigurerAdapter or antMatchers, the code is for Spring Boot 2 and will not compile on Spring Boot 3.

Customizer.withDefaults()

Customizer.withDefaults() means "turn this feature on with default settings". When you need changes, pass your own lambda instead:

.formLogin(Customizer.withDefaults())                           // defaults
.formLogin(form -> form.loginPage("/login").permitAll())         // customised

Exercise: Write a SecurityFilterChain that allows everyone to /health and /api/products/**, requires login for everything else, and supports only HTTP Basic (no login page).

Show answer
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/health", "/api/products/**").permitAll()
            .anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults());
    return http.build();
}