开发者

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

目录
  • 多个servlet时Spring security需要指明路由匹配策略
    • 原因分析
    • 修复问题
    • 路由策略区别
  • 总结

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

    项目原本是 SpringBoot-3.1.3 + druid-1.2.21 ,并且 Druid 开启了可视化监控页 stat-view-servle编程客栈t

    将项目升级到 SpringBoot-3.1.4 后,启动项目时报错。

    摘取部分内容:

    Failed to instantiate [org.springframework.security.web.SjsecurityFilterChain]: Factory method ‘filterChain&rs编程客栈quo; 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之python前的5.8版本、6.0.5之前的6.0版本和6.1.2之前的6.1版本可能容易受到授权规则错误配置的影响。

    即除了 DispatcherServlet 以外,还存在其他 Servlet 时, Spring security 的路由匹配策略需要明确哪些路由模式是Spring MVC的。

    修复问题

    • 例如旧版uBmGBRRPyk放行路径使用的是
    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 都可以正确匹配到。

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜