Spring Security過濾器鏈如何匹配到特定的請求
過濾器通過上一篇文章知道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為什么能夠重復使用。