当前位置:网站首页>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
边栏推荐
猜你喜欢
一键清理项目下pycharm和Jupyter缓存文件
【学习】从零开始的音视频开发(9)——NuPlayer
LeetCode简单题之计算字符串的数字和
校园转转二手市场源码下载
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
[untitled]
Samsung, March to the west again
Transformer-XL: Attentive Language ModelsBeyond a Fixed-Length Context 论文总结
在MATLAB中快速画圆(给出圆心坐标和半径就能直接画的那种)
社区团购小程序源码+界面diy+附近团长+供应商+拼团+菜谱+秒杀+预售+配送+直播
随机推荐
CSV column extract column extraction
Listed on the Shenzhen Stock Exchange: the market value is 5.2 billion yuan. Lu is the East and his daughter is American
Comparison of indoor positioning methods of several intelligent robots
扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...
AQS & ReentrantLock 实现原理
每周leetcode - 06 数组专题 7~739~50~offer 62~26~189~9
An idea plug-in that doesn't work, but can install X
CGM优化血糖监测管理——移宇科技亮相四川省国际医学交流促进会
Positioning of high precision welding manipulator
1216_ MISRA_ C standard learning notes_ Rule requirements for control flow
通过实现参数解析器HandlerMethodArgumentResolver接口来自定义注解
LeetCode简单题之重新排列日志文件
LeetCoed18. Sum of four numbers
vslam PPT
Solidity IDE Remix中文版使用手册
The whole house intelligence bet by the giant is driving the "self revolution" of Hisense, Huawei and Xiaomi
JS common array methods
An article understands variable lifting
nn.Module类的讲解
干货!以点为形:可微分的泊松求解器