领先一步
VMware 提供培训和认证,助您加速进步。
了解更多Spring Security 5.2 的发布包括了对 DSL 的增强,允许使用 Lambda 配置 HTTP 安全性。
需要注意的是,之前的配置风格仍然有效并受支持。Lambda 的添加旨在提供更大的灵活性,但其使用是可选的。
您可能在 Spring Security 的文档或示例中见过这种配置风格。让我们来看看使用 Lambda 配置 HTTP 安全性与之前的配置风格有何不同。
使用 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());
}
}
不使用 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();
}
}
比较上述两个示例,您会注意到一些关键区别
.and() 方法来链式配置选项。在调用 Lambda 方法后,HttpSecurity 实例会自动返回以进行进一步配置。withDefaults() 使用 Spring Security 提供的默认值启用安全功能。这是 Lambda 表达式 it -> {} 的快捷方式。您也可以以类似的方式使用 Lambda 配置 WebFlux 安全性。下面是一个使用 Lambda 的配置示例。
@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();
}
}
Lambda DSL 的创建旨在实现以下目标
.and() 链式连接配置选项。