領先一步
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()
連結配置選項。