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

输入/输出系统

The third divisor of leetcode simple question

PyQt5开发之QTableWidget表头自定义与美化(附源代码下载)

干货!以点为形:可微分的泊松求解器

My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together

dried food! Point based: differentiable Poisson solver

AAAI 2022招募讲者啦!!

stm32以及freertos 堆栈解析

Qt编译QtXlsx库

clang 如何产生汇编文件
随机推荐
5.6 综合案例-RTU-
Discussion on ES6 tail tune optimization
渗透测试面试合集---HVV---
[untitled]
vslam PPT
单点登录 SSO
[appium] encountered the problem of switching the H5 page embedded in the mobile phone during the test
C language learning record -- use and analysis of string function (2)
Flatten arrays
My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together
1216_MISRA_C规范学习笔记_控制流的规则要求
室内定位技术对比
Search the complete navigation program source code
浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda
一篇文章看懂变量提升(hoisting)
[go] common concurrency model [generic version]
LeetCode简单题之统计字符串中的元音子字符串
C outputs a two-dimensional array with the following characteristics.
有意思的js 代码
PyQt5开发之QTableWidget表头自定义与美化(附源代码下载)