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

Spring Boot Security:仅对指定URL(/api/**)启用JWT过滤器求助

解决Spring Boot Security中JWT过滤器仅对/api/**生效的问题

方法一:修改自定义JWT过滤器,内部判断过滤范围

你的customJwtAuthenticationFilter当前会拦截所有请求,核心原因是没有限定它的生效URL范围。可以通过重写过滤器的过滤判断逻辑来解决:

  1. 确保自定义过滤器继承OncePerRequestFilter,然后重写shouldNotFilter方法,跳过非/api/**开头的请求:
public class CustomJwtAuthenticationFilter extends OncePerRequestFilter {

    // 保留原有的JWT验证逻辑代码...

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // 对非/api/**开头的请求不执行过滤操作
        return !request.getServletPath().startsWith("/api/");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 原有的JWT令牌解析、身份验证逻辑...
    }
}
  1. 原configure方法无需修改,addFilterBefore依然保留,过滤器内部会自行判断是否执行逻辑。

方法二:通过FilterRegistrationBean指定过滤器生效路径

如果不想修改过滤器代码,也可以在配置类中通过注册Bean的方式限定路径:

  1. 在Security配置类中添加过滤器注册Bean:
@Bean
public FilterRegistrationBean<CustomJwtAuthenticationFilter> jwtFilterRegistration() {
    FilterRegistrationBean<CustomJwtAuthenticationFilter> registrationBean = new FilterRegistrationBean<>();
    registrationBean.setFilter(customJwtAuthenticationFilter);
    // 指定仅对/api/**路径的请求生效
    registrationBean.addUrlPatterns("/api/**");
    return registrationBean;
}
  1. 注意:此时需要删除原configure方法中的.addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);代码,避免过滤器被重复添加到Security过滤链中。

两种方法的区别

  • 方法一更贴合Spring Security的过滤链设计,利用OncePerRequestFilter的特性确保一次请求仅执行一次过滤判断。
  • 方法二则是通过Servlet容器的过滤器注册机制控制范围,适合需要更灵活配置多个路径规则的场景。

内容的提问来源于stack exchange,提问作者Định Chiểu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:55:15