使用多個servlet時Spring security需要指明路由匹配策略問題
多個servlet時Spring security需要指明路由匹配策略
項目原本是 SpringBoot-3.1.3
+ druid-1.2.21
,并且 Druid
開啟了可視化監(jiān)控頁 stat-view-servlet
。
將項目升級到 SpringBoot-3.1.4
后,啟動項目時報錯。
摘取部分內(nèi)容:
Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method ‘filterChain’ threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).
This is because there is more than one mappable servlet in your servlet context: {org.springframework.web.servlet.DispatcherServlet=[/], com.alibaba.druid.support.jakarta.StatViewServlet=[/druid/*]}.
原因分析
錯誤信息可以看出來配置 Spring security
的放行策略時路由匹配的策略選擇不當,
根據(jù)spring官方在關于 CVE-2023-34035
的安全報告中提到
Spring Security versions 5.8 prior to 5.8.5, 6.0 prior to 6.0.5 and 6.1 prior to 6.1.2 could be susceptible to authorization rule misconfiguration if the application uses or and multiple servlets, one of them being Spring MVC’s DispatcherServlet.
如果應用程序使用或和多個servlet(其中一個是Spring MVC的DispatcherServlet),則Spring Security 5.8.5之前的5.8版本、6.0.5之前的6.0版本和6.1.2之前的6.1版本可能容易受到授權規(guī)則錯誤配置的影響。
即除了 DispatcherServlet
以外,還存在其他 Servlet
時, Spring security
的路由匹配策略需要明確哪些路由模式是Spring MVC的。
修復問題
- 例如舊版放行路徑使用的是
http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/user/register").permitAll())
- 改為
// MvcRequestMatcher策略 authorize.requestMatchers(new MvcRequestMatcher(new HandlerMappingIntrospector(), "/user/register")).permitAll() // AntPathRequestMatcher策略 authorize.requestMatchers(new AntPathRequestMatcher("/user/register")).permitAll()
其中 MvcRequestMatcher
和 AntPathRequestMatcher
是兩種不同的匹配規(guī)則。
具體概念不再贅述,核心點就是 MvcRequestMatcher
基于 DispatcherServlet
進行匹配。
路由策略區(qū)別
調(diào)整放行 Druid
的路徑,使用 MvcRequestMatcher
策略匹配,正常啟動。
但是訪問網(wǎng)頁的時候發(fā)現(xiàn)放行沒生效,被 Spring security
攔截了,需要認證才能訪問,調(diào)整為 AntPathRequestMatcher
則是正常放行。
因為 Druid
提供了自己的監(jiān)控數(shù)據(jù)的 Servlet
,其是作為一個獨立的 Servlet
映射到容器中,而并非通過 DispatcherServlet
,所以放行 Druid
就需要使用 AntPathRequestMatcher
方式。
authorize.requestMatchers(new AntPathRequestMatcher("/druid/**")).permitAll()
而對于 Swagger
,通常它的頁面和API文檔都會被包括在 Spring MVC
的控制器里面,并且其URL路徑會通過 @RequestMapping
注解映射,所以使用 MvcRequestMatcher
和 AntPathRequestMatcher
都可以正確匹配到。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringMVC使用MultipartFile實現(xiàn)文件上傳
這篇文章主要為大家詳細介紹了SpringMVC使用MultipartFile實現(xiàn)文件上傳功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04thymeleaf實現(xiàn)前后端數(shù)據(jù)交換的示例詳解
Thymeleaf?是一款用于渲染?XML/XHTML/HTML5?內(nèi)容的模板引擎,當通過?Web?應用程序訪問時,Thymeleaf?會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示,這篇文章主要介紹了thymeleaf實現(xiàn)前后端數(shù)據(jù)交換,需要的朋友可以參考下2022-07-07