配置迁移
以下步骤涉及如何配置 HttpSecurity
、WebSecurity
及相关组件的更改。
使用 Lambda DSL
Lambda DSL 自 Spring Security 5.2 版本起引入,它允许使用 lambda 表达式来配置 HTTP 安全性。
你可能在 Spring Security 文档或示例中见过这种配置风格。让我们来看看 HTTP 安全的 lambda 配置与之前的配置风格有何不同。
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/blog/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(formLogin -> formLogin
.loginPage("/login")
.permitAll()
)
.rememberMe(Customizer.withDefaults());
return http.build();
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.requestMatchers("/blog/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.rememberMe();
return http.build();
}
}
Lambda DSL 是配置 Spring Security 的首选方式,之前的配置风格在 Spring Security 7 中将不再有效,届时将要求使用 Lambda DSL。这样做的主要原因有以下几点:
-
以前的方式在不知道返回类型的情况下,不清楚正在配置的是什么对象。嵌套越深,情况就越混乱。即使是有经验的用户也会认为他们的配置在做一件事,而实际上它做的是另一件事。
-
一致性。许多代码库在这两种风格之间切换,导致不一致,使得理解配置变得困难,并且经常导致配置错误。
Lambda DSL 配置技巧
在比较上述两个样本时,您会注意到一些关键差异:
-
在 Lambda DSL 中,不需要使用
.and()
方法来链式配置选项。调用 lambda 方法后,HttpSecurity
实例会自动返回以进行进一步的配置。 -
Customizer.withDefaults()
使用 Spring Security 提供的默认值来启用安全功能。这是 lambda 表达式it → {}
的快捷方式。
WebFlux 安全性
你也可以使用类似的方式通过 lambda 表达式配置 WebFlux 安全性。以下是一个使用 lambda 表达式的配置示例。
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.pathMatchers("/blog/**").permitAll()
.anyExchange().authenticated()
)
.httpBasic(Customizer.withDefaults())
.formLogin(formLogin -> formLogin
.loginPage("/login")
);
return http.build();
}
}
Lambda DSL 的目标
Lambda DSL 的创建旨在实现以下目标:
-
自动缩进使配置更具可读性。
-
无需使用
.and()
链式配置选项。 -
Spring Security DSL 的配置风格与其他 Spring DSL(如 Spring Integration 和 Spring Cloud Gateway)类似。
使用 .with()
代替 .apply()
自定义 DSL
在 6.2 版本之前,如果你有一个自定义 DSL,你会使用 HttpSecurity#apply(…)
方法将其应用到 HttpSecurity
上。然而,从 6.2 版本开始,该方法已被弃用,并将在 7.0 版本中移除,因为一旦 .and()
被移除(参见 github.com/spring-projects/spring-security/issues/13067),将不再可能使用 .and()
来链式配置。相反,建议使用新的 .with(…)
方法。有关如何使用 .with(…)
的更多信息,请参阅自定义 DSLs 部分。