当前位置:网站首页>JWT工具类
JWT工具类
2022-07-02 05:51:00 【想吃凤梨酥】
创建JWT工具类
引入依赖
<!--jwt依赖-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
创建 JwtUtil 工具类
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工具类 */
public class JwtUtil {
//有效期为
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文
public static final String JWT_KEY = "xiuhui";
public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}
/** * 生成jtw * @param subject token中要存放的数据(json格式) * @return */
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
return builder.compact();
}
/** * 生成jtw * @param subject token中要存放的数据(json格式) * @param ttlMillis token超时时间 * @return */
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
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) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("sg") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate);
}
/** * 创建token * @param id * @param subject * @param ttlMillis * @return */
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
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);
}
/** * 生成加密后的秘钥 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;
}
/** * 解析 * * @param jwt * @return * @throws Exception */
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}
}
使用
创建,以token返回前端
String adminId = loginUser.getAdmin().getId().toString();
String jwt= JwtUtil.createJWT(adminId);
Map<String,Object> map=new HashMap<>();
map.put("securityToken",jwt);
return map;
解析,查看是否过期
//解析token
String adminId =null;
try {
Claims claims = JwtUtil.parseJWT(token);
adminId = claims.getSubject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("token非法");
}
边栏推荐
- 2022-2-14 learning xiangniuke project - Section 6 displays login information
- Common protocols and download paths of NR
- Oled12864 LCD screen
- Stick to the big screen UI, finereport development diary
- Zzuli:1060 numbers in reverse order
- 495.提莫攻击
- PHP read file (read the specified line containing a string in the file)
- Conglin environmental protection rushes to the scientific and Technological Innovation Board: it plans to raise 2billion yuan, with an annual profit of more than 200million yuan
- php获取cpu使用率、硬盘使用、内存使用
- Software testing - concept
猜你喜欢

With an amount of $50billion, amd completed the acquisition of Xilinx

Thunder on the ground! Another domestic 5g chip comes out: surpass Huawei and lead the world in performance?

如何写出好代码 — 防御式编程指南

2022-2-15 learning xiangniuke project - Section 8 check login status

mysql事务和隔离级别

brew install * 失败,解决方法

all3dp.com网站中全部Arduino项目(2022.7.1)
![[personal test] copy and paste code between VirtualBox virtual machine and local](/img/ce/eaf0bd9eff6551d450964da72e0b63.jpg)
[personal test] copy and paste code between VirtualBox virtual machine and local

Oled12864 LCD screen

数理统计与机器学习
随机推荐
Cambrian was reduced by Paleozoic venture capital and Zhike shengxun: a total of more than 700million cash
php继承(extends)
php获取cpu使用率、硬盘使用、内存使用
php按照指定字符,获取字符串中的部分值,并重组剩余字符串为新的数组
Fundamentals of software testing
1037 Magic Coupon
php读文件(读取文件内含有某字符串的指定行)
1036 Boys vs Girls
Applet jumps to official account
idea開發工具常用的插件合集匯總
文件包含漏洞(一)
ThreadLocal memory leak
Grbl software: basic knowledge of simple explanation
php读文件(读取json文件,转换为数组)
495.提莫攻击
PHP development and testing WebService (soap) -win
Simply encapsulate JS and apply it
Typora installation (no need to enter serial number)
1035 Password
[paper translation] gcnet: non local networks meet squeeze exception networks and beyond