Spring Security 5.2 對 Lambda DSL 語法的加強,容許使用lambda配置HttpSecurity
、ServerHttpSecurity
spring
重要提醒,以前的配置方法仍然有效。lambda的添加旨在提供更大的靈活性,可是用法是可選的。讓咱們看一下HttpSecurity
的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());
}
}複製代碼
@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();
}
}複製代碼
Lambda DSL配置技巧比較上面的兩個樣本時,您會注意到一些關鍵差別:ide
在Lambda DSL中,無需使用.and()
方法連接配置選項。HttpSecurity
調用Lambda
方法以後實例自動返回進行進一步的配置。ui
@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();
}
}複製代碼
Spring SecurityLambda DSL 自動縮進使配置更具可讀性、不須要使用連接配置選項.and()。Spring Security DSL
與其餘Spring DSL
(例如Spring Integration和Spring Cloud Gateway)具備相似的配置方法。spa