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

Spring Boot 3.0.0中如何放行/auth路径?antMatchers等方法失效

Spring Boot 3.0(Spring Security 6.x)下正确放行/auth路径的配置方案

问题核心原因

Spring Boot 3.0对应Spring Security 6.x版本,该版本已移除antMatcher/antMatchers方法,统一使用requestMatchers;你之前的配置错误地将请求方法作为requestMatchers的第二个路径参数,导致规则不匹配,请求被默认的authenticated()拦截返回403。

正确配置示例

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // 启用CORS(若需自定义可替换为自定义CorsConfigurationSource)
        .cors(Customizer.withDefaults())
        // 禁用CSRF(无状态接口场景建议禁用)
        .csrf(csrf -> csrf.disable())
        // 授权规则配置
        .authorizeHttpRequests(auth -> auth
            // 放行指定请求方法的/auth/login
            .requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
            // 放行整个/auth路径下的所有请求(可选,根据需求选择)
            .requestMatchers("/auth/**").permitAll()
            // 其余所有请求需认证
            .anyRequest().authenticated()
        )
        // 配置无状态会话
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        // 自定义认证提供者
        .authenticationProvider(authenticationProvider())
        // 添加JWT过滤器(注意过滤器内部需放行/auth路径)
        .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

关键细节说明

  1. requestMatchers的正确用法

    • 指定请求方法时,必须通过HttpMethod枚举类传入,如requestMatchers(HttpMethod.POST, "/auth/login");也可使用AntPathRequestMatcher实例:.requestMatchers(new AntPathRequestMatcher("/auth/login", "POST"))。
    • 若需放行整个/auth/**路径的所有请求方法,直接写.requestMatchers("/auth/**").permitAll()即可。
  2. JWT过滤器的额外处理
    你的jwtAuthFilter可能会拦截所有请求进行token校验,需在过滤器内部添加逻辑:当请求路径匹配/auth/**时,直接放行,不执行token验证逻辑,示例如下:

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();
        // 放行/auth路径下的请求
        if (path.startsWith("/auth/")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 其余请求执行JWT校验逻辑
        // ... 你的token验证代码
    }
    
  3. 排查步骤

    • 先临时移除addFilterBefore(jwtAuthFilter, ...),测试/auth/login是否能正常访问,若能则说明是过滤器拦截了请求。
    • 开启Spring Security debug日志(在application.properties中添加logging.level.org.springframework.security=DEBUG),查看请求的匹配规则执行过程,确认放行规则是否生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:35:25