在 Spring Security 5.2 中增强了 DSL 的功能:允许使用 Lambda 表达式来配置 HTTP security 。
需要注意的是:先前版本的配置风格仍然是有效的且受支持的。Spring 官方额外新增 Lambda 表达式是为了提高代码的灵活性,只是一个可选的用法。
下面让我们看一下 Lambda 表达式配置 HTTP security 和先前的配置风格的对比。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected 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 {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/blog/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().rememberMe();}
}
对比上述两种配置风格,你会注意到一些关键的不同点:
在 Lambda 风格中,不再需要通过 .and()
方法来串联配置项。
在调用 Lambda 方法后,HttpSecurity
对象 http
会自动返回以继续执行进一步的配置。
方法 withDefaults()
可以使用 Spring Security 提供的默认值启用安全功能。这是 Lambda 表达式 it -> {}
的快捷方式。
此外,你还可以使用 Lambda 表达式来配置 WebFlux security ,配置方式与上面基本相似。
举个例子:
@EnableWebFluxSecurity
public class SecurityConfig {@BeanSecurityWebFilterChain 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()
方法来串联配置项。