Spring Security Lambda DSL Configuration Explained
Spring Security lambda DSL explained: why and() chaining was replaced, how to write authorizeHttpRequests, formLogin and csrf with lambdas.

Open a Spring Security configuration written in 2019 and the first thing you notice is a staircase of and() calls. Open one written for Spring Security 7 and the staircase is gone, because the method that made it possible was removed. This post explains why the lambda DSL replaced the chain, how to read it, and how to convert an old class without changing what it allows. Examples target Spring Security 7 with Spring Boot 4 on Java 25.
Why the chain had to go
The old style was one long fluent call. Every feature method returned a configurer, and and() climbed back up to HttpSecurity so you could start the next feature.
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.csrf().disable();Nothing in that code stops you from putting a call under the wrong parent. Indentation was a convention, not a rule, and the compiler could not tell .loginPage("/login") on the form login apart from one meant for the logout configurer. Reviewers had to count and() calls in their heads. In a file with eight features, that is where mistakes lived.
The lambda DSL fixes this by making scope a language construct. Each feature method takes a Customizer<T>, and whatever you do inside the lambda can only touch that feature.
The same rules in lambda form
@Configuration
@EnableWebSecurity
class WebSecurityConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login")
.permitAll())
.logout(logout -> logout
.logoutSuccessUrl("/"))
.csrf(Customizer.withDefaults());
return http.build();
}
}Customizer<T> is a functional interface from T to void. That is all the magic there is. The parameter in form -> form.loginPage("/login") is the form login configurer, and nothing outside the lambda can see it. A misplaced setting is now a compile error or a visible nesting problem, not a silent attachment to the wrong feature.
The chain between features still exists, but it is the plain return value of http.formLogin(...), which is HttpSecurity again. Nothing is climbing a tree.
Defaults and switching things off
Most features work with no settings at all. Customizer.withDefaults() is the lambda that does nothing, and it turns the feature on:
http.httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));Turning a feature off has two spellings:
http.csrf(csrf -> csrf.disable());
http.csrf(AbstractHttpConfigurer::disable);They behave identically. Use the method reference when the lambda would only call disable(). Disable CSRF protection only for APIs that are stateless and authenticate with a header token, because a browser that sends cookies automatically is exactly what CSRF protection exists for. The reasoning is in preventing CSRF.
What else changed with the method names
The lambda DSL arrived alongside several renames. Old code usually needs all of them at once, so it helps to see them together.
| Old | Current |
|---|---|
authorizeRequests() | authorizeHttpRequests(...) |
antMatchers, mvcMatchers, regexMatchers | requestMatchers |
.and() | removed, nest instead |
extends WebSecurityConfigurerAdapter | a SecurityFilterChain bean |
The last row is a separate migration with its own traps, covered in migrating WebSecurityConfigurerAdapter and configuring a SecurityFilterChain. The release notes for the version that removed and() are summarized in what changed in Spring Security 7.
One behavior difference deserves a flag. authorizeHttpRequests evaluates rules in the order you write them and stops at the first match, and so did authorizeRequests. But the new method authorizes every dispatch type by default, including forwards and error dispatches, where the old one did not. If an old application relied on error pages being open without a rule, add .dispatcherTypeMatchers(DispatcherType.ERROR).permitAll() ahead of the catch-all.
Several chains in one application
A real application often has two security stories: a stateless API and a browser site. Define one chain for each and let securityMatcher decide which requests a chain owns.
@Bean
@Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.securityMatcher("/api/**")
.authorizeHttpRequests(a -> a.anyRequest().hasAuthority("SCOPE_api"))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
@Bean
@Order(2)
SecurityFilterChain site(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
}The lowest @Order that matches wins, and a chain with no securityMatcher matches everything. Put the specific chain first and the catch-all last. If the catch-all comes first, the API chain is dead code and nothing warns you.
A migration that does not change behavior
Treat the conversion as a refactoring with a safety net, not a rewrite.
- Write tests for the access rules first. A
@WebMvcTestwith@WithMockUserand one request per rule is enough to pin down what the current configuration allows. - Replace
authorizeRequests()withauthorizeHttpRequests(...)and move the rules inside a lambda. - Turn each
.feature().a().b().and()into.feature(f -> f.a().b()). Do it one feature at a time and compile between each. - Swap the matcher methods for
requestMatchers. On Spring MVC applications this picks the right matcher for each path, so check any path with a servlet prefix. - Delete leftover
and()calls. The compiler finds them for you in Spring Security 7. - Run the tests again. A rule that used to pass by accident now fails loudly, and that is the point.
The common surprise in step 4 is an antMatchers("/admin") that used to match /admin/ with a trailing slash. Since Spring Framework 6, trailing slash matching is off by default, so /admin/ no longer matches /admin. Add the second pattern if you still need it.
Keeping the bean readable
A configuration with ten features still fits on one screen if each nested lambda is short. When a block grows, extract it:
private static void rules(AuthorizeHttpRequestsConfigurer<HttpSecurity>
.AuthorizationManagerRequestMatcherRegistry auth) {
auth.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}Then call http.authorizeHttpRequests(WebSecurityConfig::rules). The method reference works because the lambda is a Customizer. It reads better than a 30 line lambda, and the long generic type is a good reason to leave short rules inline.
Test the chain you configured
A security configuration without a test is a configuration you only trust until the next refactoring. A web slice that imports the configuration checks the rules as a client sees them, including the ones you meant to be closed:
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class SecurityRulesTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders;
@Test
void anonymousIsRejected() throws Exception {
mvc.perform(get("/api/orders")).andExpect(status().isUnauthorized());
}
@Test
void tokenWithReadScopeCanList() throws Exception {
mvc.perform(get("/api/orders").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders:read"))))
.andExpect(status().isOk());
}
@Test
void tokenWithReadScopeCannotWrite() throws Exception {
mvc.perform(post("/api/orders").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders:read")))
.contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isForbidden());
}
}The three tests pin the shape of the rules: no credentials gives 401, enough authority gives 200, and valid credentials without the right authority give 403. When you migrate from the chained style to the lambda form, run these tests before and after, and the migration is proven not to have changed behavior. To see why a request was treated as it was, set logging.level.org.springframework.security=DEBUG and read the list of filters the request passed through, since the filter that rejected it is named in the log.
Where this stops mattering
Applications that act only as an OAuth 2 resource server can configure much of this through properties such as spring.security.oauth2.resourceserver.jwt.issuer-uri and never write a chain at all. Boot's auto-configuration builds the chain from them, and the DSL only matters once you need to deviate. The reference for every feature method is the Spring Security Java configuration chapter, and the Customizer Javadoc is short enough to read in full.


