自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Security過濾器鏈如何匹配到特定的請求

開發(fā) 架構(gòu)
只有滿足了SecurityFilterChain的match方法的請求才能被該SecurityFilterChain處理,那如何配置才能讓一個SecurityFilterChain處理特定的路徑呢?

過濾器通過上一篇文章知道SecurityFilterChain決定了哪些請求經(jīng)過的過濾器鏈,那么SecurityFilterChain是如何匹配到特定請求的呢?今天胖哥就來帶你揭開這個秘密,還希望各位同學能夠點贊、再看、轉(zhuǎn)發(fā)來一波。

如何攔截特定的請求

只有滿足了SecurityFilterChain的match方法的請求才能被該SecurityFilterChain處理,那如何配置才能讓一個SecurityFilterChain處理特定的路徑呢?

RequestMatcher

HttpSecurity內(nèi)置了RequestMatcher屬性來處理路徑匹配問題。RequestMatcher可總結(jié)為以下幾大類:

使用Ant路徑:

 httpSecurity.antMatcher("/foo/**");

如果你配置了全局的Servlet Path的話,例如/v1,配置ant路徑的話就要/v1/foo/**,使用MVC風格可以保持一致:

 httpSecurity.mvcMatcher("/foo/**");

另外MVC風格可以自動匹配后綴,例如/foo/hello可以匹配/foo/hello.do、/foo/hello.action 等等。另外你也可以使用正則表達式來進行路徑匹配:

 httpSecurity.regexMatcher("/foo/.+");

如果上面的都滿足不了需要的話,你可以通過HttpSecurity.requestMatcher方法自定義匹配規(guī)則;如果你想匹配多個規(guī)則的話可以借助于HttpSecurity.requestMatchers方法來自由組合匹配規(guī)則,就像這樣:

    httpSecurity.requestMatchers(requestMatchers ->
requestMatchers.mvcMatchers("/foo/**")
.antMatchers("/admin/*get"));

一旦你配置了路徑匹配規(guī)則的話,你會發(fā)現(xiàn)默認的表單登錄404了,因為默認是/login,你加了前綴后當然訪問不到了。

使用場景

比如你后臺管理系統(tǒng)和前端應用各自走不同的過濾器鏈,你可以根據(jù)訪問路徑來配置各自的過濾器鏈。例如:

    /**
* Admin 過濾器鏈.
*
* @param http the http
* @return the security filter chain
* @throws Exception the exception
*/
@Bean
SecurityFilterChain adminSecurityFilterChain(HttpSecurity http) throws Exception {
http.requestMatchers(requestMatchers -> requestMatchers.mvcMatchers("/admin/**"))
//todo 其它配置
return http.build();
}

/**
* App 過濾器鏈.
*
* @param http the http
* @return the security filter chain
* @throws Exception the exception
*/
@Bean
SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
http.requestMatchers(requestMatchers -> requestMatchers.mvcMatchers("/app/**"));
//todo 其它配置
return http.build();
}

另外也可以使用該特性降低不同規(guī)則URI之間的耦合性。

思考一下HttpSecurity這個Spring Bean為什么能夠重復使用。


責任編輯:武曉燕 來源: 碼農(nóng)小胖哥
相關(guān)推薦

2022-02-21 23:58:49

Spring過濾器順序值

2022-02-10 14:54:31

Spring容器過濾器

2022-02-16 23:58:41

Spring過濾器驗證碼

2021-11-11 07:38:15

服務器過濾器框架

2024-01-05 09:04:35

隆過濾器數(shù)據(jù)結(jié)構(gòu)哈希函數(shù)

2017-04-12 14:43:01

Spring ClouZuul過濾器

2023-01-26 01:41:27

核心全局過濾器

2021-07-05 15:22:03

Servlet過濾器客戶端

2009-06-18 10:13:00

Hibernate過濾

2009-07-08 17:33:37

Servlet過濾器

2024-11-04 08:45:48

布隆過濾器元數(shù)據(jù)指紋值

2017-05-04 22:30:17

Zuul過濾器微服務

2021-01-14 08:13:39

Spring Clou應用內(nèi)置過濾器

2009-07-08 15:30:56

Servlet過濾器

2009-07-08 16:07:04

Servlet過濾器配

2009-09-29 13:55:23

Hibernate設置

2009-07-14 09:09:08

Swing模型過濾器

2011-06-29 16:14:59

Qt 事件 過濾器

2016-12-07 09:56:13

JavaFilter過濾器

2025-04-21 00:50:50

點贊
收藏

51CTO技術(shù)棧公眾號