jjwt - 为什么我的代码会跳过try语句直接进入catch?
问题描述
我正在尝试解码用户输入的 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
}
}
}
解决方案
我的猜测是,您用于创建令牌的密钥在验证令牌时并不相同。
openssl rand -base64 32
应该创建一个随机密钥,但这些字符不太可能是可打印的。它看起来像http://jwtbuilder.jamiekurtz.com/
使用直接输入文本字段的密钥,而不是首先对其进行 base 64 解码。我从来没有使用过那个网站,所以这只是一个猜测。
这实质上意味着其中一个关键是:
byte[] key = Base64.getDecoder().decode("b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=");
另一个是:
byte[] key = "b8SwFJZVgo+S5Cuhf5LWUeXpHxDm5mp30GCuQHX2TpY=".getBytes()
第一个选项是一个更好的做法,但我猜当你这个网站时,你会想要使用第二个选项。
推荐阅读
- c++ - 如何修复二元运算符
- java - KStreams:你如何获得记录的(起源)主题?
- python - 如何根据行号从文件中选择特定行?
- javascript - 有没有办法在不使用 Json 的情况下将 int 元素的数组列表从 javascritp 发送到 spring contoller?
- laravel - Laravel - 按字母顺序
- ios - 整数数组到范围数组
- couchbase - 对 CouchBase 编程的热情
- c# - 有没有办法总是将实体模型中的字符串数据成员转换为 char(n)?
- javascript - 如何避免 Angular observable 中的“InternalError: too much recursion”?
- python - 如何使用python请求通过登录页面登录?