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

求助:Next.js Middleware无法验证Java Spring Boot后端的JWT

解决JWT签名验证失败(JWSSignatureVerificationFailed)问题

核心问题排查与修复方案

  • 修正Cookie取值方式
    你当前的代码中,request.cookies.get('jwt')返回的是Cookie对象而非纯token字符串,直接传入jwtVerify会导致验证失败。需要提取value属性:

    const token = request.cookies.get('jwt')?.value;
    if (!token) {
      // 处理无token的路由拦截逻辑
    }
    const { payload } = await jwtVerify(
      token,
      new TextEncoder().encode(process.env.SECRET_KEY)
    );
    
  • 统一密钥编码逻辑
    Spring默认会将字符串密钥按UTF-8转成字节数组,但旧版本可能存在隐式处理差异。建议在Spring中显式指定编码,确保和jose库的编码逻辑完全对齐:

    import io.jsonwebtoken.Keys;
    import java.nio.charset.StandardCharsets;
    
    public static String generateJwtToken(AppUser user) {
        Map<String, Object> claims = new HashMap<>();
    
        return Jwts.builder()
            .setClaims(claims)
            .setSubject(user.getUsername())
            .setIssuedAt(new Date(System.currentTimeMillis()))
            .setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000))
            .signWith(Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS512)
            .compact(); 
    }
    
  • 验证密钥一致性
    分别在Spring和Next.js中打印密钥的Base64编码值,确认两者完全相同:

    • Spring端:Base64.getEncoder().encodeToString(jwtSecret.getBytes(StandardCharsets.UTF_8))
    • Next.js端:Buffer.from(new TextEncoder().encode(process.env.SECRET_KEY)).toString('base64')
      若结果不一致,检查.env文件中是否存在多余空格、换行或转义字符。
  • 确认JWT格式完整性
    在Next.js中间件中打印token值,用JWT解析工具验证:

    • Header中的alg字段必须为HS512
    • Token没有被截断、转义或篡改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:45:54