Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Filter Chain and Configuration

The SecurityFilterChain Bean and the Lambda DSL

Write modern Spring Security configuration with a SecurityFilterChain bean, HttpSecurity and lambda customizers, and migrate old WebSecurityConfigurerAdapter code.

Modern Spring Security configuration is a method that takes an HttpSecurity builder, configures it with a series of lambdas, and returns http.build(). That method is annotated @Bean and returns a SecurityFilterChain. This lesson explains the shape of that code, what each line adds to the filter chain, how to read the common options, and how to convert older configuration.

Read the previous lesson on the filter chain first: the DSL is simply a convenient way to choose which filters go into the chain and how they are configured.

The basic shape

Java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain appChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/css/**", "/login").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/home", false))
            .logout(logout -> logout
                .logoutSuccessUrl("/login?bye"))
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

Each call such as formLogin(...) receives a customizer: a lambda that configures one configurer object. Customizer.withDefaults() means "enable it with the defaults". HttpSecurity is a builder: all the calls collect settings, and http.build() turns the settings into the filter list. Nothing is applied until build().

@EnableWebSecurity is not strictly required with Boot (auto-configuration does it), but it documents intent and many tutorials include it.

Lambda DSL versus the old style

Old configuration used chained calls with .and():

Java
// Removed style: do not write this any more
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
          .antMatchers("/admin/**").hasRole("ADMIN")
          .anyRequest().authenticated()
        .and()
        .formLogin()
        .and()
        .csrf().disable();
}

It was hard to see where one setting ended and the next began. The lambda DSL fixes that by nesting: each customizer is a block, and indentation shows structure. The migration table:

Old New
extends WebSecurityConfigurerAdapter, override configure(HttpSecurity) A @Bean SecurityFilterChain method
authorizeRequests() authorizeHttpRequests(...)
antMatchers, mvcMatchers, regexMatchers requestMatchers(...)
.and() Not needed: use lambdas
configure(WebSecurity) with ignoring() Prefer permitAll() in the chain
configure(AuthenticationManagerBuilder) Define UserDetailsService/AuthenticationProvider beans
@EnableGlobalMethodSecurity @EnableMethodSecurity

What common options add

A mental map of configurers to filters:

Configurer Effect
authorizeHttpRequests Adds AuthorizationFilter with your rules
formLogin Adds UsernamePasswordAuthenticationFilter and the login page filters
httpBasic Adds BasicAuthenticationFilter
logout Adds LogoutFilter
csrf Adds CsrfFilter (enabled by default)
cors Adds CorsFilter
headers Configures HeaderWriterFilter
sessionManagement Session policy, fixation protection, concurrency
exceptionHandling Entry point and access denied handler for ExceptionTranslationFilter
oauth2ResourceServer Adds the bearer token filter
securityMatcher Limits which requests this chain applies to

The order of configuration calls does not change the filter order: the framework sorts filters itself. The order of rules inside authorizeHttpRequests does matter, and that is the subject of request matchers and rules.

Stateless API configuration

A REST API used by mobile apps and other servers typically has no browser session and no login page:

Java
@Bean
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(a -> a
            .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
            .anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

Disabling CSRF is acceptable here only because requests are authenticated with an Authorization header, which a malicious web page cannot add to a cross-site request. If the same application also sets a session cookie, CSRF protection must stay. The CSRF chapter of this course explains the reasoning in depth.

The builder in miniature

To see why build() at the end matters, here is a stand-in with the same structure. A Http builder collects customizers and then, on build(), sorts the chosen filters by their fixed order (not by the order you called them), the way the framework does.

Java A tiny HttpSecurity builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output lists UsernamePasswordAuthenticationFilter before BasicAuthenticationFilter even though httpBasic was called first, and CsrfFilter is gone because we disabled it. Remember this when a tutorial seems to say that "call order matters": for filters it does not.

The session creation policy used above has four values. This stand-in applies each to a login request and a plain request, so you can see when an HttpSession would exist.

Java Session creation policies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common DSL options you will use constantly

Java
http.formLogin(f -> f.loginPage("/login").permitAll());
http.logout(l -> l.logoutUrl("/signout").deleteCookies("JSESSIONID"));
http.exceptionHandling(e -> e.accessDeniedPage("/denied"));
http.headers(h -> h.frameOptions(fo -> fo.sameOrigin()));   // e.g. for an H2 console
http.requiresChannel(c -> c.anyRequest().requiresSecure()); // redirect HTTP to HTTPS
http.securityMatcher("/api/**");                            // this chain handles only /api/**

Two warnings. frameOptions(sameOrigin) weakens clickjacking protection and exists for tools such as an embedded H2 console; do not carry it into production. And requiresChannel is usually better handled by the proxy or load balancer, with server.forward-headers-strategy set so Spring knows the original scheme.

Several beans: one per concern

You are free to define more than one SecurityFilterChain; see multiple filter chains. Even in a single-chain application, keep the configuration class small and readable, and extract a method per concern if it grows beyond a screen.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which replaces extends WebSecurityConfigurerAdapter in current Spring Security?

    The adapter was removed. You declare a SecurityFilterChain bean and configure it through HttpSecurity.
  2. 2. You call httpBasic(...) before formLogin(...). Which filter runs first?

    The framework sorts filters by a built-in order, so call order is irrelevant for filters.
  3. 3. What does Customizer.withDefaults() mean in formLogin(Customizer.withDefaults())?

    It is a no-op customizer: the feature is turned on but nothing is changed.
  4. 4. When is it acceptable to disable CSRF protection?

    Browsers attach cookies automatically, which is what CSRF exploits. A header-only API is not vulnerable that way.

Summary

  • Configuration is a @Bean SecurityFilterChain method using HttpSecurity and lambda customizers, ending with http.build().
  • The old adapter, antMatchers and .and() style are gone; use requestMatchers and nested lambdas.
  • Each configurer adds, removes or tunes filters; the filter order is fixed by the framework.
  • The order of authorization rules matters; the order of configurer calls does not.
  • A stateless header-token API may disable CSRF and sessions; a cookie-based app must not.

Next: Request matchers and authorization rules