Spring Boot 3.1.2配置SecurityFilterChain时requestMatchers报错
Spring Boot 3.1.2 Spring Security 配置错误解决方法
错误原因
该错误是因为Spring Security无法自动识别配置的路径模式类型,尤其是在添加@EnableWebMvc注解的场景下,必须明确指定请求匹配器的类型,避免歧义。
解决方案
方案一:使用MvcRequestMatcher(推荐适配Spring MVC端点)
通过注入HandlerMappingIntrospector创建MvcRequestMatcher,专门匹配Spring MVC端点:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc public class SecurityConfig { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(UserDetailsService detailsService) { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(detailsService); return new ProviderManager(daoAuthenticationProvider); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher registerMatcher = new MvcRequestMatcher(introspector, "/auth/register"); return http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests((auth) -> auth .requestMatchers(registerMatcher).permitAll() .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) .build(); } }
方案二:明确使用AntPathRequestMatcher
直接创建AntPathRequestMatcher实例,告知Spring Security使用Ant风格路径匹配:
// 其他代码保持不变,仅修改filterChain方法 @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests((auth) -> auth .requestMatchers(new AntPathRequestMatcher("/auth/register")).permitAll() .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) .build(); }
额外提示
如果项目不需要自定义WebMvc配置,可尝试移除@EnableWebMvc注解(Spring Boot默认已自动配置WebMvc),此时Spring Security可能会自动识别路径类型,无需额外指定匹配器。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

