Mastering Spring Security Lambda DSL: Cleaner Configurations with Java 8
This article explains Spring Security 5.2's Lambda DSL enhancements, compares lambda‑based and traditional configurations for HttpSecurity and ServerHttpSecurity, shows equivalent code samples, highlights default behaviors, and demonstrates the same approach for Spring Security WebFlux.
Lambda DSL Overview
Spring Security 5.2 enhances the Lambda DSL syntax, allowing the use of lambda expressions with HttpSecurity and ServerHttpSecurity. The previous configuration methods remain valid; lambda usage is optional and provides greater flexibility.
HttpSecurity
Configuring with Lambdas
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/blog/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(formLogin ->
formLogin
.loginPage("/login")
.permitAll()
)
.rememberMe(withDefaults());
}
}Equivalent Configuration Without Lambda
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/blog/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.rememberMe();
}
}Default Behavior
When using the Lambda DSL, the .and() method is unnecessary because each lambda call returns the appropriate builder, allowing fluent chaining without explicit linking.
Spring Security WebFlux
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges ->
exchanges
.pathMatchers("/blog/**").permitAll()
.anyExchange().authenticated()
)
.httpBasic(withDefaults()) // enable security with default settings
.formLogin(formLogin ->
formLogin
.loginPage("/login")
);
return http.build();
}
}Summary
Spring Security's Lambda DSL provides automatic indentation, making configurations more readable and eliminating the need for the linking .and() method. The DSL offers a concise way to configure security, similar to other Spring DSLs such as Spring Integration and Spring Cloud Gateway.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architecture Diary
Committed to sharing original, high‑quality technical articles; no fluff or promotional content.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
