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