我尝试创建JWT令牌
final String jws = Jwts.builder()
.claim("rainId", rainId.toString())
.signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.decode("jwtSecretKey"))
.compact();
然后我尝试解析它
Jws<Claims> jwsClaims = Jwts.parser()
.require("rainId", rainId.toString())
.setSigningKey(TextCodec.BASE64.decode("jwtSecretKey1"))
.parseClaimsJws(jws);
您可以看到SigningKey
稍有不同,因此我希望解析器将失败,但不会发生。仅当解析器中的SigningKey
有很大差异时才会发生。例如“ jwtSecretKey1111111111111111111111111111111111”或“ dsfdsfdsfdsfds”。有人可以解释为什么解析器中的SigningKey
稍微有些不同,为什么解析器不会失败吗?
我用
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
答案 0 :(得分:3)
您似乎没有正确使用API。
signWith()
和setSigningKey()
方法都希望使用Base64编码的String作为输入。但是您正在调用TextCodec.BASE64.decode("...")
。
jwtSecretKey
和jwtSecretKey1
看起来都不像Base64编码的字符串。但是,如果您尝试对它们进行解码,它们将产生相同的输出:
System.out.println(Arrays.toString(TextCodec.BASE64.decode("jwtSecretKey")));
System.out.println(Arrays.toString(TextCodec.BASE64.decode("jwtSecretKey1")));
[-113, 11, 82, 121, -54, -34, -76, -89, -78]
[-113, 11, 82, 121, -54, -34, -76, -89, -78]
这就是为什么签名验证不会失败的原因。
您应改为使用TextCodec.BASE64.encode("...")
,如下所示:
String jws = Jwts.builder()
.claim("rainId", rainId.toString())
.signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.encode("jwtSecretKey"))
.compact();
Jws<Claims> jwsClaims = Jwts.parser()
.require("rainId",rainId.toString())
.setSigningKey(TextCodec.BASE64.encode("jwtSecretKey1"))
.parseClaimsJws(jws);