Spring Security 5.8更新后RequestMatchers的组合配置方法
Spring Security 5.8+ 实现“匹配指定模式且排除特定模式”的过滤器配置
在Spring Security 5.8及以后版本中,虽然部分旧的RequestMatcher实现被标记为弃用,但官方提供了更灵活的组合式RequestMatcher实现来满足“匹配指定规则且排除特定规则”的需求,核心是利用逻辑组合匹配器来实现。
核心实现思路
要实现“匹配matchingMatchers中任意一个,且不匹配rejectMatchers中任意一个”的效果,可以通过以下逻辑组合:
- 用
OrRequestMatcher将所有需要包含的规则组合:只要匹配其中一个规则,就算符合包含条件 - 用
NegatedRequestMatcher对每个需要排除的规则取反:表示“不匹配该排除规则” - 用
AndRequestMatcher将取反后的排除规则组合:表示所有排除规则都不匹配 - 最后用
AndRequestMatcher将包含规则和排除规则的组合结果再组合:得到最终的匹配逻辑
代码实现
import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; // 假设你已经初始化好这两个列表 List<RequestMatcher> matchingMatchers = ...; List<RequestMatcher> rejectMatchers = ...; // 1. 组合包含规则:匹配任意一个指定模式 RequestMatcher includeMatcher = new OrRequestMatcher(matchingMatchers); // 2. 组合排除规则:所有排除模式都不匹配 RequestMatcher excludeMatcher = new AndRequestMatcher( rejectMatchers.stream() .map(NegatedRequestMatcher::new) .toList() ); // 3. 最终匹配规则:包含规则 且 排除规则 RequestMatcher finalMatcher = new AndRequestMatcher(includeMatcher, excludeMatcher); // 配置到HttpSecurity httpSecurity.securityMatcher(finalMatcher);
关键匹配器说明
OrRequestMatcher:多规则“或”逻辑,只要其中一个规则匹配,整体就匹配NegatedRequestMatcher:单规则取反,原规则匹配时它不匹配,原规则不匹配时它匹配AndRequestMatcher:多规则“与”逻辑,只有所有规则都匹配,整体才匹配
简化场景
如果你的包含/排除规则只有单个,可以简化代码:
- 单个包含规则:直接使用该
RequestMatcher,无需OrRequestMatcher - 单个排除规则:直接用
NegatedRequestMatcher包装后,和包含规则组合成AndRequestMatcher
内容的提问来源于stack exchange,提问作者Mike Rother
相关产品推荐
相关产品推荐

