当前位置:网站首页>使用JWT生成与解析Token
使用JWT生成与解析Token
2022-04-23 07:16:00 【hungry&foolish】
Jwt全称是:json web token。它将用户信息加密到token里,服务器不保存任何用户信息。服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证。
token的用处:当用户第一次登陆后,用户名密码验证成功后,服务器会生成一个token,把token返回到客户端,一般token都是储存在浏览器的localStorage 或 cookies中,存在localStorage的token需要通过js,将token添加到http请求头中,下次再访问服务器,就不需要用户名密码了,只要带上token,服务器验证token的合法性后,就能访问后端资源了。
利用JWT生成token,将userId放进去并加密
// 秘钥
static final String SECRET = "X-Litemall-Token";
// 签名是有谁生成
static final String ISSUSER = "LITEMALL";
// 签名的主题
static final String SUBJECT = "this is litemall token";
// 签名的观众
static final String AUDIENCE = "MINIAPP";
public String createToken(Integer userId){
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
Map<String, Object> map = new HashMap<String, Object>();
Date nowDate = new Date();
// 过期时间:2小时
Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
// 设置头部信息 Header
.withHeader(map)
// 设置 载荷 Payload
.withClaim("userId", userId)
.withIssuer(ISSUSER)
.withSubject(SUBJECT)
.withAudience(AUDIENCE)
// 生成签名的时间
.withIssuedAt(nowDate)
// 签名过期的时间
.withExpiresAt(expireDate)
// 签名 Signature
.sign(algorithm);
return token;
} catch (JWTCreationException exception){
exception.printStackTrace();
}
return null;
}
//解析token并在token中取出userId
public Integer verifyTokenAndGetUserId(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(ISSUSER)
.build();
DecodedJWT jwt = verifier.verify(token);
//以上的部分时验证token是否正确,verify中会进行解码,下面可以直接使用jwt去getClaims()。
/* public DecodedJWT verify(String token) throws JWTVerificationException { DecodedJWT jwt = JWT.decode(token); this.verifyAlgorithm(jwt, this.algorithm); this.algorithm.verify(jwt); this.verifyClaims(jwt, this.claims); return jwt; } */
//如果没有上面的验证,也可以直接使用JWT.decode(token)返回jwt然后再getClaims()
Map<String, Claim> claims = jwt.getClaims();
Claim claim = claims.get("userId");
return claim.asInt();
} catch (JWTVerificationException exception){
// exception.printStackTrace();
}
return 0;
}
版权声明
本文为[hungry&foolish]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_35227352/article/details/124307715
边栏推荐
- Mobile terminal layout (3D conversion, animation)
- C语言学习记录——삼십팔 字符串函数使用和剖析(2)
- Jetson Xavier NX(3)Bazel Mediapipe 安装
- 巨头押注的全屋智能,正在驱动海信、华为、小米们「自我革命」
- 华硕笔记本电脑重装系统后不能读取usb,不能上网
- C outputs a two-dimensional array with the following characteristics.
- 在线YAML转XML工具
- Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结
- ApplicationReadyEvent的使用
- [appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test
猜你喜欢
NLLLoss+log_SoftMax=CE_Loss
CGM优化血糖监测管理——移宇科技亮相四川省国际医学交流促进会
智能名片小程序名片详情页功能实现关键代码
谈谈那些基础但不简单的股票数据
Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9
LeetCode简单题之重新排列日志文件
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
vivo,硬件安全的爱与雷霆
高精度焊接机械臂定位
LeetCode简单题之三除数
随机推荐
DataBinding的使用五
Qt读取路径下所有文件或指定类型文件(含递归、判断是否为空、创建路径)
Ribbon start process
如何在SQL Server中导入excel数据,2019版
求3个字符串(每串不超过20个字符)中的最大者。
Anti shake and throttling
Asynchronous learning
Qt利用QtXlsx操作excel文件
Flatten arrays
vivo,硬件安全的爱与雷霆
LeetCode15. 三数之和
总线结构概述
Codeforces Round #784 (Div. 4)
Talking about distributed storage from ES, mongodb, redis and rocketmq
欧圣电气深交所上市:市值52亿 陆为东父女为美国籍
怎么读书读论文
Mobile web (Font Icon, plane conversion, color gradient)
Alibaba sentinel learning QA
Hump naming object
Planification du mouvement du manipulateur dans l'assemblage 3c