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

Spring Boot JWT配置异常:/authenticate等接口被拦截报Token格式错误

问题解决:调用/authenticate和/register时触发"JWT Token does not begin with Bearer String"错误

核心原因

  1. WebSecurityConfig未被Spring加载:你的WebSecurityConfig类缺少必要注解,导致Spring未识别并应用该配置,permitAll()规则未生效,JWT过滤器依然拦截所有请求。
  2. JWT过滤器未跳过无需认证的接口:即使配置生效,过滤器仍会尝试从请求头获取Token,而/authenticate和/register请求本就不需要携带Token,因此触发警告。

解决方案

1. 修复WebSecurityConfig的注解

给WebSecurityConfig类添加@Configuration和@EnableWebSecurity注解,确保Spring加载该配置类:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 原有代码保持不变
}

2. 修改JwtRequestFilter,跳过无需认证的接口

在过滤器的doFilterInternal方法开头,先判断请求路径是否为无需认证的接口,若是则直接放行,不执行Token校验:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    String requestURI = request.getRequestURI();
    // 跳过无需认证的接口
    if (requestURI.equals("/authenticate") || requestURI.equals("/register")) {
        chain.doFilter(request, response);
        return;
    }

    // 原有Token校验逻辑继续执行
    String requestTokenHeader = request.getHeader("Authorization");
    String jwtToken = null;
    String username = null;

    if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
        jwtToken = requestTokenHeader.substring(7);
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
        } catch (IllegalArgumentException e) {
            System.out.println("Unable to get JWT Token");
        } catch (ExpiredJwtException e) {
            System.out.println("JWT Token has expired");
        }
    } else {
        logger.warn("JWT Token does not begin with Bearer String");
    }

    // 后续认证逻辑...
}

3. 验证配置生效

启动项目后,调用/authenticate和/register接口时,将不再触发"JWT Token does not begin with Bearer String"警告,接口可正常处理请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:40:17