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

Spring项目使用io.jsonwebtoken生成解析JWT报错:不支持无签名明文JWT

问题解决:JJWT生成解析JWT报错处理

错误原因分析

1. Unsigned plaintext JWTs are not supported

你生成的是无签名JWT(即alg=None的unsecured类型),但调用了parseClaimsJws()方法——这个方法专门用于解析带签名的JWS(JSON Web Signature)。同时JJWT默认禁用无签名JWT,因为这种JWT完全不加密,安全性极低。

2. Signed plaintext JWSs are not supported

你添加setSigningKey()但未指定签名算法,导致生成的JWT格式不符合JWS规范。JJWT无法识别这种"仅设密钥但无算法"的畸形JWS,因此报错。

正确解决方案(推荐生产环境使用)

生成带签名的合法JWT,使用signWith()同时指定签名算法和密钥,解析时用对应密钥验证:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.util.Base64;

// 生成256位HS256签名密钥(生产环境请妥善保管密钥,不要硬编码)
SecretKey secretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode("your-256-bit-secret-key-keep-it-safe"));

// 生成带签名的JWT
String jws = Jwts.builder()
        .setSubject(user.getId())
        .signWith(secretKey, SignatureAlgorithm.HS256) // 指定签名算法与密钥
        .compact();

// 解析并验证JWT
Claims claims = Jwts.parserBuilder()
        .setSigningKey(secretKey) // 设置验证密钥
        .build()
        .parseClaimsJws(jws)
        .getBody();

String decodedSubject = claims.getSubject();
System.out.printf("decoded: %s", decodedSubject);

测试用无签名JWT方案(仅用于本地测试,禁止生产使用)

如果只是本地测试需要无签名JWT,需在解析器中启用unsecured()配置,并使用parseClaimsJwt()方法解析:

// 生成无签名JWT
String jwt = Jwts.builder()
        .setSubject(user.getId())
        .compact();

// 解析无签名JWT(需启用unsecured允许)
Claims claims = Jwts.parserBuilder()
        .unsecured() // 允许解析无签名JWT
        .build()
        .parseClaimsJwt(jwt)
        .getBody();

String decodedSubject = claims.getSubject();
System.out.printf("decoded: %s", decodedSubject);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:22:53