当前位置: 代码网 > it编程>编程语言>Java > 使用多个servlet时Spring security需要指明路由匹配策略问题

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

2024年08月14日 Java 我要评论
多个servlet时spring security需要指明路由匹配策略项目原本是 springboot-3.1.3 + druid-1.2.21 ,并且 druid 开启了可视化监控页 stat-vi

多个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 都可以正确匹配到。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com