当前位置:网站首页>使用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
边栏推荐
猜你喜欢

Vowel substring in statistical string of leetcode simple problem

An article understands variable lifting

欧圣电气深交所上市:市值52亿 陆为东父女为美国籍

浅谈ES6尾调优化

Samsung, March to the west again

Online yaml to XML tool

vslam PPT

LeetCode簡單題之計算字符串的數字和

Principle of sentinel integrating Nacos to update data dynamically

一篇文章看懂变量提升(hoisting)
随机推荐
Planification du mouvement du manipulateur dans l'assemblage 3c
js常用数组方法
js将树形结构数据转为一维数组数据
Jetson Xavier NX (3) bazel mediapipe installation
Anti shake and throttling
三星,再次“西征”
Principle of sentinel integrating Nacos to update data dynamically
【解释】get ORA-12838: cannot read/modify an object after modifying it in parallel
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
Qt读写XML文件
AAAI 2022 recruit speakers!!
PHP high precision computing
Somme numérique de la chaîne de calcul pour un problème simple de leetcode
Implementation of new
Usage of databinding
redis主从服务器问题
Mobile terminal layout (3D conversion, animation)
渗透测试面试合集---HVV---
sql 使用过的查询语句
编译原理题-带答案