Get ahead
VMware offers training and certification to turbo-charge your progress.
Learn moreThe release of Spring Security 5.2 includes enhancements to the DSL, which allow HTTP security to be configured using lambdas.
It is important to note that the prior configuration style is still valid and supported. The addition of lambdas is intended to provide more flexibility, but their usage is optional.
You may have seen this style of configuration in the Spring Security documentation or samples. Let us take a look at how a lambda configuration of HTTP security compares to the previous configuration style.
Configuration using 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 using lambdas
@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();
}
}
When comparing the two samples above, you will notice some key differences:
.and()
method. The HttpSecurity
instance is automatically returned for further configuration after the call to the lambda method.withDefaults()
enables a security feature using the defaults provided by Spring Security. This is a shortcut for the lambda expression it -> {}
.You may also configure WebFlux security using lambdas in a similar manner. Below is an example configuration using lambdas.
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges ->
exchanges
.pathMatchers("/blog/**").permitAll()
.anyExchange().authenticated()
)
.httpBasic(withDefaults())
.formLogin(formLogin ->
formLogin
.loginPage("/login")
);
return http.build();
}
}
The Lambda DSL was created to accomplish to following goals:
.and()
.