当前位置:网站首页>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非法");
}
边栏推荐
- [paper translation] gcnet: non local networks meet squeeze exception networks and beyond
- Yyds dry inventory what is test driven development
- Typora installation (no need to enter serial number)
- 2022-2-14 learning xiangniuke project - Section 7 account setting
- 深度学习分类网络 -- AlexNet
- php父类(parent)
- Thunder on the ground! Another domestic 5g chip comes out: surpass Huawei and lead the world in performance?
- all3dp.com网站中全部Arduino项目(2022.7.1)
- VSCode paste image插件保存图片路径设置
- Visual Studio導入
猜你喜欢
Reading notes of cgnf: conditional graph neural fields
Vite打包后的dist不能直接在浏览器打开吗
Cambrian was reduced by Paleozoic venture capital and Zhike shengxun: a total of more than 700million cash
5g market trend in 2020
Huawei Hongmeng OS, is it OK?
【論文翻譯】GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond
Matplotlib double Y axis + adjust legend position
Go language web development is very simple: use templates to separate views from logic
Can't the dist packaged by vite be opened directly in the browser
“簡單”的無限魔方
随机推荐
1035 Password
Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders
php按照指定字符,获取字符串中的部分值,并重组剩余字符串为新的数组
Here comes a new chapter in the series of data conversion when exporting with easyexcel!
Alibaba: open source and self-developed liquid cooling data center technology
3D 打印机 G 代码命令:完整列表和教程
LCD之MIPI协议的一些说明
[paper translation] gcnet: non local networks meet squeeze exception networks and beyond
Zzuli: maximum Convention and minimum common multiple
Win10 copy files, save files... All need administrator permission, solution
数据库学习总结5
js判断移动端还是pc端
Pytorch Basics
数据挖掘方向研究生常用网站
Yyds dry inventory what is test driven development
Vscode paste image plugin saves image path settings
With an amount of $50billion, amd completed the acquisition of Xilinx
Go language web development is very simple: use templates to separate views from logic
Several keywords in C language
KMP idea and template code