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

antMatcher().permitAll不生效,如何排除/eval/v2下指定URI?

问题分析与解决方案

你的核心问题出在两个地方:路径匹配不完整,以及自定义过滤器未排除目标URI。

1. 修正SecurityFilterChain的路径匹配

当前配置中antMatchers("/save/public/image")只匹配了路径的后半段,而目标完整URI是/eval/v2/save/public/image,Security无法识别到这是需要放行的路径,因此仍会触发认证逻辑。

修改后的Security配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    StringBuffer sb = constuctAntMatcher();
    return http.csrf().disable().cors().disable().authorizeRequests()
            .antMatchers("/eval/v1/**").authenticated()
            .antMatchers("/eval/v2/save/public/image").permitAll() // 填写完整目标路径
            .and().formLogin().disable()
            .httpBasic().disable().addFilterBefore(userIdAuthenticationFilter(), DisableEncodeUrlFilter.class)
            .build();
}

2. 让自定义过滤器跳过目标URI

Spring Security的permitAll仅表示该路径无需认证,但自定义的OncePerRequestFilter默认会拦截所有请求,因此需要在过滤器中主动排除目标路径。

修改你的UserIdAuthenticationFilter,重写shouldNotFilter方法:

public class UserIdAuthenticationFilter extends OncePerRequestFilter {
    // 可使用AntPathMatcher处理更复杂的路径匹配
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String requestUri = request.getRequestURI();
        // 匹配目标URI,返回true则跳过过滤
        return pathMatcher.match("/eval/v2/save/public/image", requestUri);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 原有的认证逻辑代码
        filterChain.doFilter(request, response);
    }
}

为什么之前的配置无效?

  • 路径匹配不完整导致Security未将目标URI标记为无需认证;
  • 自定义过滤器没有排除规则,即使Security放行,过滤器仍会执行拦截逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 00:25:59