jwt生成token和token解析基础详解
1.jwt结构
jwt生成到客户端(浏览器)的token包含"."分开的三个部分:
- header(Base64Url编码过的)
- payload(Base64Url编码过的)
- signature
形如:xxxxx.yyyyy.zzzzz
1.1 例子:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYW5keSIsImV4cCI6MTY1NTg5NzEwMCwiYWdlIjozMH0.32hfc-oBxGg2Lgk3QR48HCbadsbOfCUxexw9aiQ_FQk
拆为3部分:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.(header)
eyJuYW1lIjoiYW5keSIsImV4cCI6MTY1NTg5NzEwMCwiYWdlIjozMH0.(payload)
32hfc-oBxGg2Lgk3QR48HCbadsbOfCUxexw9aiQ_FQk(signature)
2.header+payload+signature介绍
2.1 header
上面的header部分:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9base64Url解码后:
{
"typ": "JWT",
"alg": "HS256"
}通常说明token的类型、生成token所使用的的算法
The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
2.2 Payload
上面的Payload部分:eyJuYW1lIjoiYW5keSIsImV4cCI6MTY1NTg5NzEwMCwiYWdlIjozMH0base64Url解码后:
{
"name": "andy",
"exp": 1655897100,
"age": 30
}通常是要客户端请求时带货的内容(比如用户名,比如是否是管理员等,server端生成的时候可以定义内容,形式如map)
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
2.3 Signature
上面的Signature部分:32hfc-oBxGg2Lgk3QR48HCbadsbOfCUxexw9aiQ_FQk它是用来验签的, 验证是否被客户端修改过,它的生成逻辑如下:
就是使用header部分的base64Url、payload部分的base64Url部分、小圆点、以及你的私钥密码,使用指定的算法生成的;因为有密码, 所以是安全的,这也是密码要保护好的原因。
计算逻辑如下:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
12345
)
3. java测试用例
/**
* JWT加密生成token, payload中保存 name/age
*/
@Test
public void testJwtToken() {
// 加密秘钥
final String SECRET = "12345";
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, 2);
String token = JWT.create().withClaim("name", "andy")
.withClaim("age", 30)
.withExpiresAt(c.getTime())
.sign(Algorithm.HMAC256(SECRET));
System.out.println(token);
}
/**
* JWT解密生成token, 读取payload中保存的 name/age
*/
@Test
public void testJwtVerify() {
String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYW5keSIsImV4cCI6MTY1NTg4ODk3MiwiYWdlIjozMH0.LU4AQJkld03kDhatkiiArSJI4liGiANArTvoyswzk5I";
final String SECRET = "12345";
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
DecodedJWT decodedJWT = verifier.verify(jwtToken);
Claim name = decodedJWT.getClaim("name");
Claim age = decodedJWT.getClaim("age");
System.out.println(name);
System.out.println(age);
}以上就是jwt生成token和token解析基础的详细内容,更多关于jwt生成token的资料请关注脚本之家其它相关文章!
相关文章
Spring Cloud Stream整合RocketMQ的搭建方法
本文介绍了如何使用SpringCloudStream整合RocketMQ进行消息传递,SpringCloudStream是一个用于构建与共享消息系统连接的框架,支持持久pub/sub语义和消费者组,感兴趣的朋友跟随小编一起看看吧2024-11-11
Java中BitMap(位图)hutool版、IntMap、LongMap示例详解
这篇文章主要给大家介绍了关于Java中BitMap(位图)hutool版、IntMap、LongMap的相关资料,通过位运算高效存储和检索整数,相比于传统数组,它们在内存占用和性能上都有显著优势,需要的朋友可以参考下2024-12-12


最新评论