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

Spring Security 6.1中permitAll()不生效,JwtAuthFilter异常触发

问题原因与解决方案

核心问题

你配置的permitAll()是授权规则,仅控制请求是否需要通过权限校验,不会阻止自定义过滤器(JwtAuthFilter)被触发。Spring Security过滤器链的执行顺序是:自定义过滤器 → 授权校验逻辑(FilterSecurityInterceptor),所以即使请求被标记为permitAll,JwtAuthFilter依然会先执行。

另外你调试看到RequestMatcherConfigurer的matchers为空,是因为authorizeHttpRequests里的配置是给授权阶段用的,和过滤器的拦截范围无关——自定义过滤器默认会拦截所有进入Spring Security过滤器链的请求。

解决方法

给JwtAuthFilter添加路径排除规则,让它跳过/api/auth/**路径的请求,有两种常用方式:

方式1:在过滤器内部实现路径排除

如果你的JwtAuthFilter继承自OncePerRequestFilter,重写shouldNotFilter方法:

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    AntPathMatcher pathMatcher = new AntPathMatcher();
    return pathMatcher.match("/api/auth/**", request.getServletPath());
}

这个方法返回true时,过滤器就不会处理当前请求。

方式2:在SecurityFilterChain中指定过滤器的拦截范围

在添加过滤器时,通过重载方法指定RequestMatcher,只让过滤器处理非/api/auth/**的请求:

http
    // 其他配置...
    .addFilterBefore(
        new JwtAuthFilter(jwtService),
        UsernamePasswordAuthenticationFilter.class,
        new NegatedRequestMatcher(new AntPathRequestMatcher("/api/auth/**"))
    );

补充说明

如果你需要对/api/auth/**之外的请求强制JWT校验,可以调整authorizeHttpRequests的配置:

.authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/auth/**").permitAll()
        .anyRequest().authenticated()
)

此时授权阶段会要求其他请求必须认证,但过滤器仍会先执行——JWT验证通过则放行,验证失败则返回未认证错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:22:16