Spring6迁移SpringSecurity遇空RequestMatcher错误及配置咨询
Spring Security 6.x XML配置解决"mappings cannot be empty"错误
错误原因
Spring Security 6.0重构了安全规则配置逻辑,强制要求所有安全规则必须绑定明确的RequestMatcher,不再支持旧版本中隐式的全局默认规则(比如默认匹配所有路径)。如果配置中没有显式声明路径映射,就会抛出"mappings cannot be empty"错误。
XML中定义RequestMatcher的解决方案
1. 全局匹配所有路径
如果你的旧配置是对所有路径生效,直接声明匹配所有请求的RequestMatcher即可:
<http> <!-- 显式指定匹配所有请求,解决映射为空问题 --> <request-matcher ref="anyRequestMatcher"/> <!-- 原有安全规则保留 --> <intercept-url pattern="/**" access="authenticated"/> <form-login/> <logout/> </http> <!-- 定义匹配所有请求的Bean --> <bean id="anyRequestMatcher" class="org.springframework.security.web.util.matcher.AnyRequestMatcher"/>
2. 分路径分组配置
如果需要对不同路径设置差异化规则,可以为每个规则组单独指定RequestMatcher:
<http> <!-- 匹配/api/**路径的规则组 --> <request-matcher pattern="/api/**"/> <intercept-url pattern="/api/**" access="hasRole('API_USER')"/> <oauth2-resource-server jwt/> <!-- 匹配/web/**路径的规则组 --> <request-matcher pattern="/web/**"/> <intercept-url pattern="/web/**" access="hasRole('WEB_USER')"/> <form-login login-page="/login"/> <!-- 兜底匹配剩余所有路径 --> <request-matcher ref="anyRequestMatcher"/> <intercept-url pattern="/**" access="denyAll"/> </http> <bean id="anyRequestMatcher" class="org.springframework.security.web.util.matcher.AnyRequestMatcher"/>
3. 自定义复杂匹配规则
如果需要基于请求头、HTTP方法等复杂逻辑匹配,可以自定义RequestMatcher Bean:
<http> <request-matcher ref="customRequestMatcher"/> <intercept-url pattern="/**" access="authenticated"/> </http> <bean id="customRequestMatcher" class="com.yourcompany.security.CustomRequestMatcher"> <!-- 注入自定义匹配逻辑的参数 --> <property name="allowedMethods" value="GET,POST"/> </bean>
4. 使用6.x推荐的filter-chain标签
Spring Security 6.x推荐使用<filter-chain>标签配置,同样需要指定RequestMatcher:
<security:filter-chain request-matcher-ref="anyRequestMatcher"> <security:intercept-url pattern="/**" access="authenticated"/> <security:form-login/> </security:filter-chain> <bean id="anyRequestMatcher" class="org.springframework.security.web.util.matcher.AnyRequestMatcher"/>
注意事项
- 每个
<http>或<filter-chain>块必须至少绑定一个RequestMatcher,不能依赖旧版本的隐式默认映射 - 检查旧配置中是否有遗漏的路径规则,6.x不会自动兜底未声明的路径
内容的提问来源于stack exchange,提问作者user3612610
相关产品推荐
相关产品推荐

