当前位置:网站首页>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非法");
}
边栏推荐
猜你喜欢

Fundamentals of software testing

3D printer G code command: complete list and tutorial

Visual studio import

Importation de studio visuel

文件包含漏洞(二)

Can't the dist packaged by vite be opened directly in the browser
![[golang syntax] be careful with the copy of slices](/img/5e/1c82c58940939b94d03377ebdc03e3.jpg)
[golang syntax] be careful with the copy of slices

死磕大屏UI,FineReport开发日记

Alibaba: open source and self-developed liquid cooling data center technology

"Simple" infinite magic cube
随机推荐
Financial portal related information
《CGNF: CONDITIONAL GRAPH NEURAL FIELDS》阅读笔记
Thunder on the ground! Another domestic 5g chip comes out: surpass Huawei and lead the world in performance?
mock-用mockjs模拟后台返回数据
RNN recurrent neural network
[PHP是否安装了 SOAP 扩]对于php实现soap代理的一个常见问题:Class ‘SoapClient‘ not found in PHP的处理方法
PHP array to XML
图片裁剪插件cropper.js
Visual studio import
PHP inner class name is the same as the inner class method name
1037 Magic Coupon
Yyds dry inventory what is test driven development
PHP extensions
Zzuli:1061 sequential output of digits
php内的addChild()、addAttribute()函数
Lantern Festival gift - plant vs zombie game (realized by Matlab)
all3dp.com网站中全部Arduino项目(2022.7.1)
Typora installation (no need to enter serial number)
File contains vulnerability (I)
c语言中的几个关键字