使用多个servlet时Spring security需要指明路由匹配策略

使用多个servlet时Spring security需要指明路由匹配策略

项目原本是 SpringBoot-3.1.3 + druid-1.2.21 ,并且 Druid 开启了可视化监控页 stat-view-servlet

将项目升级到 SpringBoot-3.1.4 后,启动项目时报错。摘取部分内容:

  • 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 的放行策略时路由匹配的策略选择不当,根据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版本可能容易受到授权规则错误配置的影响。

即除了 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()

其中 MvcRequestMatcherAntPathRequestMatcher 是两种不同的匹配规则。具体概念不再赘述,核心点就是 MvcRequestMatcher 基于 DispatcherServlet 进行匹配。

路由策略区别

调整放行 Druid 的路径,使用 MvcRequestMatcher 策略匹配,正常启动。但是访问网页的时候发现放行没生效,被 Spring security 拦截了,需要认证才能访问,调整为 AntPathRequestMatcher 则是正常放行。

因为 Druid 提供了自己的监控数据的 Servlet ,其是作为一个独立的 Servlet 映射到容器中,而并非通过 DispatcherServlet ,所以放行 Druid 就需要使用 AntPathRequestMatcher 方式。

authorize.requestMatchers(new AntPathRequestMatcher("/druid/**")).permitAll()

而对于 Swagger,通常它的页面和API文档都会被包括在 Spring MVC 的控制器里面,并且其URL路径会通过 @RequestMapping 注解映射,所以使用 MvcRequestMatcherAntPathRequestMatcher 都可以正确匹配到。

  • 26
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值