当前位置:网站首页>Jjwt generate token
Jjwt generate token
2022-07-27 07:36:00 【qq_ thirty-four million one hundred and thirty-five thousand si】
Realization principle

Import maven rely on
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
Create a solid object
package com.wl.study.utils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SessionInfo {
private Long userId;
private String userName;
private String token;
}
establish token Generation and analysis
package com.wl.study.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.Optional;
public class JwtUtil {
/*** * Generate token * @param sessionInfo * @return */
public static Optional<String> generateToken(SessionInfo sessionInfo){
String token = Jwts.builder()
// The theme
.setSubject(JwtConfig.JWT_SUBJECT)
// Custom properties
.claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
.claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
// Compress
.compressWith(CompressionCodecs.DEFLATE)
// Signature
.signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
.compact();
return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
}
/*** * analysis token * @param token * @return */
public static Optional<SessionInfo> parserToken(String token){
if(StringUtils.isEmpty(token)){
return Optional.empty();
}
Claims claims = Jwts.parser()
.setSigningKey(JwtConfig.JWT_SIGNING_KEY)
.parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
.getBody();
SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
if(claims.containsKey(JwtConfig.JWT_USERID)){
sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
}
if(claims.containsKey(JwtConfig.JWT_USERNAME)){
sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
}
return Optional.of(sessionInfo);
}
private static class JwtConfig{
private final static String JWT_SUBJECT ="integral";
private final static String JWT_USERID ="userId";
private final static String JWT_USERNAME ="userName";
/*** * secret key */
private final static String JWT_SIGNING_KEY = "[email protected]!&key^#";
/** * jwt The prefix of */
public static final String JWT_TOKEN_PREFIX = "Bearer ";
}
public static void main(String[] args) {
SessionInfo sessionInfo = new SessionInfo();
sessionInfo.setUserId(1L);
sessionInfo.setUserName(" Zhang Fei ");
Optional<String> optional = JwtUtil.generateToken(sessionInfo);
System.out.println(MessageFormat.format("{0}:{1}"," Generate token",optional.orElse(null)));
System.out.println(MessageFormat.format("{0}:{1}"," analysis token",JwtUtil.parserToken(optional.get())));
}
}
establish token Tool class
package com.wl.study.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.Optional;
public class JwtUtil {
/*** * Generate token * @param sessionInfo * @return */
public static Optional<String> generateToken(SessionInfo sessionInfo){
String token = Jwts.builder()
// The theme
.setSubject(JwtConfig.JWT_SUBJECT)
// Custom properties
.claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
.claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
// Compress
.compressWith(CompressionCodecs.DEFLATE)
// Signature
.signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
.compact();
return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
}
/*** * analysis token * @param token * @return */
public static Optional<SessionInfo> parserToken(String token){
if(StringUtils.isEmpty(token)){
return Optional.empty();
}
Claims claims = Jwts.parser()
.setSigningKey(JwtConfig.JWT_SIGNING_KEY)
.parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
.getBody();
SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
if(claims.containsKey(JwtConfig.JWT_USERID)){
sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
}
if(claims.containsKey(JwtConfig.JWT_USERNAME)){
sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
}
return Optional.of(sessionInfo);
}
private static class JwtConfig{
private final static String JWT_SUBJECT ="integral";
private final static String JWT_USERID ="userId";
private final static String JWT_USERNAME ="userName";
/*** * secret key */
private final static String JWT_SIGNING_KEY = "[email protected]!&key^#";
/** * jwt The prefix of */
public static final String JWT_TOKEN_PREFIX = "Bearer ";
}
public static void main(String[] args) {
SessionInfo sessionInfo = new SessionInfo();
sessionInfo.setUserId(1L);
sessionInfo.setUserName(" Zhang Fei ");
Optional<String> optional = JwtUtil.generateToken(sessionInfo);
System.out.println(MessageFormat.format("{0}:{1}"," Generate token",optional.orElse(null)));
System.out.println(MessageFormat.format("{0}:{1}"," analysis token",JwtUtil.parserToken(optional.get())));
}
}
边栏推荐
- Multithreading [preliminary - Part 1]
- (2022 Hangdian multi school III) 1011.taxi (Manhattan maximum + 2 points)
- Use Popen to execute a command and get the return result
- Codeforces Round #810 (Div.2) A-C
- Actual combat of flutter - Request encapsulation (I)
- C language pthread_ cleanup_ Push() and pthread_ cleanup_ Pop() function (used for the resource cleaning task after the termination action in the critical resource program segment to avoid deadlock. T
- 电子量产项目框架--基本思想
- oracle清理含有引用分区的表的数据库磁盘空间
- QT连接sqlite数据库的错误及其修改办法
- Single arm routing (explanation + experiment)
猜你喜欢

Clickhouse notes 1 | introduction, features | installation and use based on centos7 system | common data types | mergetree table engine | SQL operation

Help send a recruitment, base all over the country. If you are interested, you can come and have a look

C common function integration-2

Using docker in MAC to build Oracle database server

Actual combat of flutter - Request encapsulation (I)

Plato farm is expected to further expand its ecosystem through elephant swap

(2022 Niuke multi school III) a-ancestor (LCA)

ClickHouse 笔记1 | 简介、特点 | 基于CentOS7系统的安装与使用 | 常用数据类型 | MergeTree 表引擎 | SQL操作

利用 Amazon DynamoDB 和 Amazon S3 结合 gzip 压缩,最大化存储玩家数据

(2022 Niuke multi school III) j-journey (Dijkstra)
随机推荐
Introduction to network -- overview of VLAN and trunk
Want to sink into redis hash and write in the attributes and values of the object. Do the bosses have a demo?
[wsl2] configure the USB camera connecting the USB device and using the host
Zabbix: map collected values to readable statements
帮忙发一份招聘,base全国,有兴趣的可以过来看看
Routing between VLANs (explanation + verification)
Summary of several common ways to join dimension tables in Flink
Systematic explanation of unit testing: mockito
DRConv-pytorch改称输出和输入一样的尺寸
flink去重(一)flink、flink-sql中常见的去重方案总结
Analysis of memory structure of C program code
Drconv pytorch is changed to the same size of output and input
安装tensorflow
View the dmesg log before server restart
MySQL2
QT连接sqlite数据库的错误及其修改办法
Graylog 日志服务器单节点部署
(2022杭电多校三)1011.Taxi(曼哈顿最值+二分)
Prior Attention Enhanced Convolutional Neural Network Based Automatic Segmentation of Organs at Risk
A small cotton padded jacket with air leakage