Spring Security配置报错:无法识别请求匹配模式类型
解决Spring Security中SecurityFilterChain配置的请求匹配器类型错误
这个异常是因为Spring Security无法自动识别你配置的请求路径属于Spring MVC路由规则还是Ant风格匹配规则,必须显式指定使用的请求匹配器类型,以下是两种可行的解决方式:
方式一:使用MvcRequestMatcher(适配Spring MVC项目)
如果你的项目基于Spring MVC开发,推荐使用这种方式,它会遵循Spring MVC的路由规则进行匹配:
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); return http .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(authorize -> authorize .requestMatchers(mvcMatcherBuilder.post("/auth/login")).permitAll() .requestMatchers(mvcMatcherBuilder.post("/auth/register")).permitAll() .requestMatchers(mvcMatcherBuilder.post("/product")).hasRole("ADMIN") .anyRequest().authenticated() ) .build(); } }
需要注入HandlerMappingIntrospector来获取Spring MVC的路由映射信息,确保匹配逻辑和项目的MVC路由一致。
方式二:使用AntPathRequestMatcher(通用匹配规则)
如果项目未使用Spring MVC,或者需要Ant风格的路径匹配(比如/api/**这类通配符),可以显式使用AntPathRequestMatcher:
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(authorize -> authorize .requestMatchers(new AntPathRequestMatcher("/auth/login", HttpMethod.POST.name())).permitAll() .requestMatchers(new AntPathRequestMatcher("/auth/register", HttpMethod.POST.name())).permitAll() .requestMatchers(new AntPathRequestMatcher("/product", HttpMethod.POST.name())).hasRole("ADMIN") .anyRequest().authenticated() ) .build(); } }
这种方式直接指定使用Ant风格的匹配规则,兼容性更强,适合非MVC场景或需要自定义匹配逻辑的情况。
内容的提问来源于stack exchange,提问作者JamesB
相关产品推荐
相关产品推荐

