Spring Security 5.2 对 Lambda DSL 语法的加强,容许使用lambda配置HttpSecurity
、ServerHttpSecurity
spring
重要提醒,以前的配置方法仍然有效。lambda的添加旨在提供更大的灵活性,可是用法是可选的。让咱们看一下HttpSecurity
的lambda配置与之前的配置样式相比。安全
@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());
}
}复制代码
@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();
}
}复制代码
Lambda DSL配置技巧比较上面的两个样本时,您会注意到一些关键差别:ide
在Lambda DSL中,无需使用.and()
方法连接配置选项。HttpSecurity
调用Lambda
方法以后实例自动返回进行进一步的配置。ui
@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();
}
}复制代码
Spring SecurityLambda DSL 自动缩进使配置更具可读性、不须要使用连接配置选项.and()。Spring Security DSL
与其余Spring DSL
(例如Spring Integration和Spring Cloud Gateway)具备相似的配置方法。spa