Spring Boot Security迁移:将mvcMatchers适配至Spring Boot 3
Spring Boot 3 下Spring Security无权限资源配置迁移方案
旧版本(Spring Boot 2及更早)配置代码
以下是旧版本中使用mvcMatchers配置指定接口无需权限校验的代码:
SecurityFilterChain unsecuredResources(HttpSecurity httpSecurity) throws Exception { httpSecurity // .requestMatchers((matchers) -> matchers .mvcMatchers("/v1/api/smartmeter/hb/guid") .mvcMatchers("/v1/api/smartmeter/hb/check-mpan")) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()); return httpSecurity.build(); }
迁移至Spring Boot 3的正确配置
Spring Boot 3对应Spring Security 6.x,其中mvcMatchers已被标记为废弃,且配置逻辑有调整,你尝试的代码问题在于多次调用authorizeHttpRequests会覆盖之前的规则,而非叠加。以下是几种正确的迁移写法:
写法1:简化路径匹配
直接在requestMatchers中传入多个路径,链式完成授权配置:
SecurityFilterChain unsecuredResources(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeHttpRequests(authorize -> authorize .requestMatchers("/v1/api/smartmeter/hb/guid", "/v1/api/smartmeter/hb/check-mpan").permitAll() .anyRequest().permitAll()); return httpSecurity.build(); }
写法2:基于MVC规则的严格匹配
如果需要严格遵循Spring MVC的路径匹配规则(比如考虑控制器的@RequestMapping前缀、路径变量解析等),可以使用MvcRequestMatcher:
@Autowired private HandlerMappingIntrospector handlerMappingIntrospector; SecurityFilterChain unsecuredResources(HttpSecurity httpSecurity) throws Exception { httpSecurity .requestMatchers(matchers -> matchers .requestMatchers(new MvcRequestMatcher(handlerMappingIntrospector, "/v1/api/smartmeter/hb/guid")) .requestMatchers(new MvcRequestMatcher(handlerMappingIntrospector, "/v1/api/smartmeter/hb/check-mpan"))) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()); return httpSecurity.build(); }
写法3:保留类似旧版的分组匹配逻辑
也可以沿用旧版的分组匹配写法,替换为antMatchers:
SecurityFilterChain unsecuredResources(HttpSecurity httpSecurity) throws Exception { httpSecurity .requestMatchers(matchers -> matchers .antMatchers("/v1/api/smartmeter/hb/guid", "/v1/api/smartmeter/hb/check-mpan")) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()); return httpSecurity.build(); }
关键注意事项
- 避免多次调用
authorizeHttpRequests,所有授权规则应在同一个lambda表达式中配置,否则后续调用会覆盖之前的规则。 mvcMatchers已废弃,优先使用requestMatchers或MvcRequestMatcher实现路径匹配。
内容的提问来源于stack exchange,提问作者Gaurav Shah
相关产品推荐
相关产品推荐

