当前位置:网站首页>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非法");
}
边栏推荐
- Common protocols and download paths of NR
- [Chongqing Guangdong education] selected reading reference materials of British and American literature of Nanyang Normal University
- PHP array to XML
- Stick to the big screen UI, finereport development diary
- Zzuli:1062 greatest common divisor
- 500. 键盘行
- 文件包含漏洞(一)
- mock-用mockjs模拟后台返回数据
- Balsamiq wireframes free installation
- 简单封装 js并应用
猜你喜欢

DRM display framework as I understand it

File contains vulnerabilities (II)

Cambrian was reduced by Paleozoic venture capital and Zhike shengxun: a total of more than 700million cash
![[technical notes-08]](/img/52/0aff21b01ba7adbfcdb597d1aa85f9.png)
[technical notes-08]

Lantern Festival gift - plant vs zombie game (realized by Matlab)

all3dp. All Arduino projects in com website (2022.7.1)
![[golang syntax] be careful with the copy of slices](/img/5e/1c82c58940939b94d03377ebdc03e3.jpg)
[golang syntax] be careful with the copy of slices
![[whether PHP has soap extensions installed] a common problem for PHP to implement soap proxy: how to handle class' SoapClient 'not found in PHP](/img/25/73f11ab2711ed2cc9f20bc7f9116b6.png)
[whether PHP has soap extensions installed] a common problem for PHP to implement soap proxy: how to handle class' SoapClient 'not found in PHP

2022-2-14 learning xiangniuke project - Section 7 account setting

死磕大屏UI,FineReport开发日记
随机推荐
RNN recurrent neural network
php父类(parent)
php按照指定字符,获取字符串中的部分值,并重组剩余字符串为新的数组
Gcnet: non - local Networks meet Squeeze excitation Networks and Beyond
Lantern Festival gift - plant vs zombie game (realized by Matlab)
Balsamiq wireframes free installation
软件测试基础篇
Test case
Appnuim environment configuration and basic knowledge
数据挖掘方向研究生常用网站
Huawei Hongmeng OS, is it OK?
Visual Studio導入
1037 Magic Coupon
php读文件(读取文件内含有某字符串的指定行)
XSS basic content learning (continuous update)
Youth training camp -- database operation project
深度学习分类网络--Network in Network
CNN可视化技术 -- CAM & Grad-CAM详解及pytorch简洁实现
Win10 copy files, save files... All need administrator permission, solution
PHP extensions