我正在尝试解码用户输入的 JWT 令牌字符串并验证签名,我正在使用 io.jsonwebtoken 库。我通过在终端中使用“openssl rand -base64 32”命令获得了“密钥”。我目前正在使用“ http://jwtbuilder.jamiekurtz.com ”来计算标头和有效负载。然后我在 jwtbuilder 网站的 Key 字段中输入我的“密钥”,如下面链接中的图片所示:
jwtbuilder.com 具有所需的标头、有效负载和签名
这是我运行代码时的输出:
package com.okta.developer;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.util.Base64;
import java.util.Scanner;
public class JWTexercise
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
byte[] key = Base64.getDecoder().decode("b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=");
System.out.println("Enter your JWT token: ");
String jwtString = input.nextLine();
Jws<Claims> jws;
try
{
// we can safely trust the JWT
jws = Jwts.parser() // (1)
.setSigningKey(Keys.hmacShaKeyFor(key)) // (2)
.parseClaimsJws(jwtString); // (3)
System.out.println("The decoded JWT token id listed below:");
System.out.println(jws);
System.out.println();
System.out.println("The signature is verified!");
}
catch (JwtException ex)
{
System.out.println("Cannot trust JWT because the signature is not verified!");
// we *cannot* use the JWT as intended by its creator
}
}
}