当前位置:网站首页>Generate and parse tokens using JWT
Generate and parse tokens using JWT
2022-04-23 08:18:00 【hungry&foolish】
Jwt The full name is :json web token. It encrypts user information to token in , The server does not save any user information . The server verifies... By using the saved key token The correctness of the , As long as it's right, it's verified .
token Usefulness : When the user logs in for the first time , After the user name and password are verified successfully , The server will generate a token, hold token Return to client , commonly token Are stored in the browser localStorage or cookies in , There is localStorage Of token Need to pass through js, take token Add to http Request header , Visit the server next time , You don't need a username or password , Just bring it token, Server authentication token After the legitimacy of , You can access back-end resources .
utilize JWT Generate token, take userId Put it in and encrypt
// Secret key
static final String SECRET = "X-Litemall-Token";
// Who generated the signature
static final String ISSUSER = "LITEMALL";
// The subject of the signature
static final String SUBJECT = "this is litemall token";
// Signed audience
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();
// Expiration time :2 Hours
Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
// Set header information Header
.withHeader(map)
// Set up load Payload
.withClaim("userId", userId)
.withIssuer(ISSUSER)
.withSubject(SUBJECT)
.withAudience(AUDIENCE)
// When the signature was generated
.withIssuedAt(nowDate)
// When the signature expires
.withExpiresAt(expireDate)
// Signature Signature
.sign(algorithm);
return token;
} catch (JWTCreationException exception){
exception.printStackTrace();
}
return null;
}
// analysis token And in token Remove from 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);
// The above part is verified token Whether it is right ,verify Will be decoded in , You can directly use jwt Go to 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; } */
// Without the above verification , It can also be used directly JWT.decode(token) return jwt And then again 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://yzsam.com/2022/04/202204230715449211.html
边栏推荐
- Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
- Install MySQL for Ubuntu and query the average score
- WordPress love navigation theme 1.1.3 simple atmosphere website navigation source code website navigation source code
- 华硕笔记本电脑重装系统后不能读取usb,不能上网
- Situational leaders - Chapter 7, solving performance problems
- 为什么会存在1px问题?怎么解决?
- C language learning record -- use and analysis of string function (2)
- Flatten arrays
- 搜一下导航完整程序源码
- [untitled]
猜你喜欢

Why are there 1px problems? How?

Weekly leetcode - 06 array topics 7 ~ 739 ~ 50 ~ offer 62 ~ 26 ~ 189 ~ 9

社区团购小程序源码+界面diy+附近团长+供应商+拼团+菜谱+秒杀+预售+配送+直播

Samsung, March to the west again

LeetCode中等题之旋转函数

一键清理项目下pycharm和Jupyter缓存文件

一款拥有漂亮外表的Typecho简洁主题_Scarfskin 源码下载

岛屿的个数

输入/输出系统

CSV column extract column extraction
随机推荐
几种智能机器人室内定位方法对比
Qt读写XML文件
synchronized 实现原理
一篇文章看懂变量提升(hoisting)
php生成短链接:将数字转成字母,将字母转成数字
Somme numérique de la chaîne de calcul pour un problème simple de leetcode
Reverse linked list exercise
clang 如何产生汇编文件
Compiler des questions de principe - avec des réponses
[effective go Chinese translation] function
ApplicationReadyEvent的使用
【无标题】
LeetCode简单题之重新排列日志文件
Vowel substring in statistical string of leetcode simple problem
The whole house intelligence bet by the giant is driving the "self revolution" of Hisense, Huawei and Xiaomi
Qt利用QtXlsx操作excel文件
Planification du mouvement du manipulateur dans l'assemblage 3c
万物互联下如何对设备进行加密
Why are there 1px problems? How?
Comparison of indoor positioning technology