Spring Security多HttpSecurity配置失效:URL匹配异常求助
问题原因分析
你遇到的问题核心在于多个HttpSecurity配置的匹配范围没有明确划分,导致优先级更高的FirstWaveFilters处理了所有请求,完全跳过了SecondWaveFilters。
具体来说:
- 你的
FirstWaveFilters虽然在授权规则里写了antMatchers("/HQ/test_web/**").anonymous(),但这只是在该配置内部定义了这个路径的授权规则,并没有限制整个配置仅对/HQ/test_web/**路径生效。 - Spring Security中,当存在多个
WebSecurityConfigurerAdapter配置时,会按照@Order的优先级依次匹配请求:如果优先级高的配置没有限定处理的路径范围,它会默认处理所有请求,后续优先级低的配置就完全没有执行的机会。
解决方案
修改FirstWaveFilters,通过http.antMatcher("/HQ/test_web/**")来明确指定这个配置仅处理/HQ/test_web/**开头的请求。这样其他路径的请求就会流转到SecondWaveFilters中处理。
修改后的FirstWaveFilters代码:
@Configuration @Order(1) public static class FirstWaveFilters extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { // 先指定该配置仅匹配 /HQ/test_web/** 路径 http.antMatcher("/HQ/test_web/**") .authorizeRequests() .anyRequest().anonymous() // 因为已经限定了路径,这里用anyRequest即可 .and() .addFilterBefore(new CustomFilter(), BasicAuthenticationFilter.class); } }
额外注意事项
antMatchervsantMatchers的区别:http.antMatcher(...)是用来限定整个HttpSecurity配置的请求匹配范围,属于配置级别的路径过滤。authorizeRequests().antMatchers(...)是在当前配置内部,针对授权规则的路径匹配,属于规则级别的过滤。
- 保持
@Order的正确性:优先级数字越小,优先级越高,确保FirstWaveFilters的@Order(1)在SecondWaveFilters的@Order(2)之前。 - 检查
SecondWaveFilters中的冗余配置:你的第二个配置里有重复的http.csrf().disable()和http.authorizeRequests().antMatchers("/**").permitAll(),建议整理成更简洁的形式,避免规则冲突:@Configuration @Order(2) public static class SecondWaveFilters extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors() .and() .csrf().disable() .authorizeRequests() .antMatchers("/h2-console/**").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll() .anyRequest().authenticated() .and() .addFilter(new JWTAuthenticationFilter(authenticationManager())) .addFilter(new JWTAuthorizationFilter(authenticationManager())) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .headers().frameOptions().disable(); } }
内容的提问来源于stack exchange,提问作者Andrej Georgiev
相关产品推荐
相关产品推荐

