Spring Security使用Lambda DSL配置流程詳解
1. 概述
在 Spring Security 5.2 中增強了 DSL 的功能:允許使用 Lambda 表達式來配置 HTTP security 。
需要注意的是:先前版本的配置風格仍然是有效的且受支持的。Spring 官方額外新增 Lambda 表達式是為了提高代碼的靈活性,只是一個可選的用法。
下面讓我們看一下 Lambda 表達式配置 HTTP security 和先前的配置風格的對比。
2. 新老配置風格對比
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 風格中,不再需要通過 .and() 方法來串聯(lián)配置項。
在調(diào)用 Lambda 方法后,HttpSecurity 對象 http 會自動返回以繼續(xù)執(zhí)行進一步的配置。
方法 withDefaults() 可以使用 Spring Security 提供的默認值啟用安全功能。這是 Lambda 表達式 it -> {} 的快捷方式。
3. WebFlux Security
此外,你還可以使用 Lambda 表達式來配置 WebFlux security ,配置方式與上面基本相似。
舉個例子:
@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();
}
}
4. Lambda DSL的目標
Lambda DSL 被開發(fā)出來,是為了完成以下的目的:
- 自動縮進以提高配置的可讀性。
- 不再需要使用
.and()方法來串聯(lián)配置項。 - Spring Security DSL 與其他 Spring DSLs (例如 Spring Integration 和 Spring Cloud Gateway ) 擁有相似的配置風格。
到此這篇關于Spring Security使用Lambda DSL配置流程詳解的文章就介紹到這了,更多相關Spring Security Lambda DSL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
RxJava+Retrofit+Mvp實現(xiàn)購物車
這篇文章主要為大家詳細介紹了RxJava+Retrofit+Mvp實現(xiàn)購物車功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
SpringMVC中Model和ModelAndView的EL表達式取值方法
下面小編就為大家分享一篇SpringMVC中Model和ModelAndView的EL表達式取值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
string boot 與 自定義interceptor的實例講解
下面小編就為大家分享一篇string boot 與 自定義interceptor的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
鴻蒙HarmonyOS App開發(fā)造輪子之自定義圓形圖片組件的實例代碼
這篇文章主要介紹了鴻蒙HarmonyOS App開發(fā)造輪子之自定義圓形圖片組件,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01

