当前位置:网站首页>使用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
边栏推荐
猜你喜欢
随机推荐
Fibula dynamic programming
Reverse linked list exercise
Principle of sentinel integrating Nacos to update data dynamically
[go]常见的并发模型[泛型版]
vivo,硬件安全的爱与雷霆
浅谈ES6尾调优化
[go] common concurrency model [generic version]
CSV Column Extract列提取
Samsung, March to the west again
Hierarchical output binary tree
clang 如何产生汇编文件
編譯原理題-帶答案
LeetCode简单题之统计字符串中的元音子字符串
Usage of databinding
1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
NFT ecological development of Ignis public chain: unicorn Donation and development of Art
常用正则表达式
ASAN 极简原理
校园转转二手市场源码下载
剑指offer day24 数学(中等)