如何为不同路径分别配置Basic认证和自定义JWT认证过滤器
问题根因
当前写法存在Spring Security过滤器链匹配规则覆盖问题:在同一个HttpSecurity实例上调用antMatcher("/jwtAuth/**")时,会将整个过滤器链的生效范围限定为仅匹配/jwtAuth/**路径,之前配置的/basicAuth/**、/signIn等路径都不会进入该过滤器链处理,自然Basic认证失效。
修复方案(Spring Boot 2.x+/Spring Security 5.x+ 推荐写法)
配置两个独立的SecurityFilterChain Bean,分别负责JWT认证路径和Basic认证路径,通过优先级区分匹配顺序,避免规则冲突:
@Configuration public class SecurityConfig { @Bean @Order(1) // 优先级更高,优先匹配jwt路径 public SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) throws Exception { http.antMatcher("/jwtAuth/**") .authorizeRequests() .anyRequest().authenticated() .and() .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .csrf().disable(); return http.build(); } @Bean @Order(2) // 匹配除jwt路径外的所有剩余路径 public SecurityFilterChain basicSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/signIn").permitAll() .antMatchers("/basicAuth/**").hasAnyAuthority(SOMEROLE) .anyRequest().authenticated() .and() .httpBasic() .and() .csrf().disable(); return http.build(); } // 原有JWT过滤器的Bean定义 @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } }
备选方案(单过滤器链实现)
如果不想拆分多个过滤器链,也可以在自定义的JwtAuthenticationFilter内部新增路径判断逻辑,仅当请求路径匹配/jwtAuth/**时才执行JWT校验,否则直接放行到后续过滤器:
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 先判断是否属于JWT认证路径范围 String requestPath = request.getRequestURI(); if (!requestPath.startsWith("/jwtAuth/")) { filterChain.doFilter(request, response); return; } // 原有JWT校验逻辑... }
内容的提问来源于stack exchange,提问作者DENIZ TOPRAK
相关产品推荐
相关产品推荐

