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