领先一步
VMware 提供培训和认证,以加速您的进步。
了解更多Spring Security 5.2 的发布包含了对 DSL 的增强,允许使用 lambda 表达式配置 HTTP 安全性。
重要的是要注意,之前的配置风格仍然有效并受支持。 添加 lambda 表达式旨在提供更大的灵活性,但它们的使用是可选的。
您可能在 Spring Security 文档或示例中看到过这种配置风格。 让我们看看 HTTP 安全性的 lambda 配置与之前的配置风格相比如何。
使用 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()
链接配置选项。