当前位置:网站首页>JWT tool class
JWT tool class
2022-07-02 05:56:00 【Want to eat pineapple crisp】
establish JWT Tool class
Introduce dependencies
<!--jwt rely on -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
establish JwtUtil Tool class
package com.liu.goods.utils.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
/** * JWT Tool class */
public class JwtUtil {
// Valid for
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 An hour
// Set secret key plaintext
public static final String JWT_KEY = "xiuhui";
public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}
/** * Generate jtw * @param subject token Data to be stored in (json Format ) * @return */
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// Set expiration time
return builder.compact();
}
/** * Generate jtw * @param subject token Data to be stored in (json Format ) * @param ttlMillis token Timeout time * @return */
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// Set expiration time
return builder.compact();
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid) // Unique ID
.setSubject(subject) // The theme It can be JSON data
.setIssuer("sg") // Issuer
.setIssuedAt(now) // The issuance of time
.signWith(signatureAlgorithm, secretKey) // Use HS256 Symmetric encryption algorithm signature , The second parameter is the secret key
.setExpiration(expDate);
}
/** * establish token * @param id * @param subject * @param ttlMillis * @return */
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// Set expiration time
return builder.compact();
}
public static void main(String[] args) throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg";
Claims claims = parseJWT(token);
System.out.println(claims);
}
/** * Generate the encrypted secret key secretKey * @return */
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/** * analysis * * @param jwt * @return * @throws Exception */
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}
}
Use
establish , With token Back to front
String adminId = loginUser.getAdmin().getId().toString();
String jwt= JwtUtil.createJWT(adminId);
Map<String,Object> map=new HashMap<>();
map.put("securityToken",jwt);
return map;
analysis , Check to see if it's overdue
// analysis token
String adminId =null;
try {
Claims claims = JwtUtil.parseJWT(token);
adminId = claims.getSubject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("token illegal ");
}
边栏推荐
- How to write good code - Defensive Programming Guide
- Vscode paste image plugin saves image path settings
- 页面打印插件print.js
- 软件测试答疑篇
- Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders
- How to change the IP address of computer mobile phone simulator
- Zzuli:1061 sequential output of digits
- 3D 打印机 G 代码命令:完整列表和教程
- “簡單”的無限魔方
- TI毫米波雷达学习(一)
猜你喜欢

3D 打印机 G 代码命令:完整列表和教程

Fundamentals of software testing

"Simple" infinite magic cube

文件包含漏洞(一)

Reading notes of cgnf: conditional graph neural fields

Summary of MySQL constraints

PHP 开发与测试 Webservice(SOAP)-Win

ESP8266与STC8H8K单片机联动——天气时钟

all3dp.com网站中全部Arduino项目(2022.7.1)

Eco express micro engine system has supported one click deployment to cloud hosting
随机推荐
数理统计与机器学习
Zzuli:1064 encrypted characters
495.提莫攻击
Several keywords in C language
神机百炼3.54-染色法判定二分图
php内类名称与类内方法名相同
STC8H8K系列汇编和C51实战——串口发送菜单界面选择不同功能
Stc8h8k series assembly and C51 actual combat - digital display ADC, key serial port reply key number and ADC value
TypeScript的泛型和泛型约束
php数组转化为xml
PHP extensions
1035 Password
使用HBuilderX的一些常用功能
51单片机——ADC讲解(A/D转换、D/A转换)
CNN可视化技术 -- CAM & Grad-CAM详解及pytorch简洁实现
Reading notes of cgnf: conditional graph neural fields
js判断移动端还是pc端
Zzuli:1068 binary number
DRM display framework as I understand it
PHP read file (read the specified line containing a string in the file)