You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Spring Security全局过滤器仅对指定路径(如Springfox页面)不生效

可行实现方案

方案1:在自定义过滤器内实现路径排除(最稳妥,无配置冲突)

如果你的AuthenticationFilter继承了Spring提供的OncePerRequestFilter基类,直接重写shouldNotFilter方法,复用你已有的忽略路径匹配逻辑即可:

public class AuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // 直接使用你已定义好的忽略路径匹配器,匹配成功则不执行当前过滤器
        return SecurityServletRequestMatchers.servletIgnoreAuthMatcher().matches(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 保留原有身份校验、填充CustomApiToken的逻辑
        CustomApiToken token = parseTokenFromRequest(request);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}

该方案不需要修改原有Spring Security配置,路径规则完全复用现有逻辑,不会和其他安全规则冲突。

方案2:调整Spring Security配置与过滤器注册逻辑

你之前的配置不生效核心原因有两个:

  1. HttpSecurity的antMatcher/requestMatcher是指定当前安全规则链的生效范围,同时配置/**和忽略路径匹配器,会导致规则链仅对忽略路径生效
  2. 如果你给AuthenticationFilter加了@Component等Spring托管注解,过滤器会被自动注册到Servlet全局过滤器链,不受Spring Security的ignoring配置控制

对应修改方法:

  • 移除AuthenticationFilter类上的@Component、@Bean等Spring托管注解,仅在安全配置类中手动实例化过滤器加入Spring Security链
  • 保留你最开始的配置即可,WebSecurity.ignoring()配置的路径会自动跳过整个Spring Security过滤器链,不会触发你自定义的身份校验过滤器
private static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .antMatcher("/**")
            .addFilterBefore(new AuthenticationFilter(), BasicAuthenticationFilter.class)
            .authorizeRequests()
            .anyRequest().authenticated();
    }

    @Override
    public void configure(WebSecurity web) {
        web
           .ignoring()
               .requestMatchers(SecurityServletRequestMatchers.servletIgnoreAuthMatcher());
    }
}

补充校验

确认SecurityServletRequestMatchers.servletIgnoreAuthMatcher()已包含所有Swagger相关路径,常见需要忽略的路径如下:

  • /swagger-ui/**
  • /v2/api-docs
  • /v3/api-docs/**
  • /swagger-resources/**
  • /webjars/**

内容的提问来源于stack exchange,提问作者RMSD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 20:03:02