当前位置:网站首页>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 ");
}
边栏推荐
- 1037 Magic Coupon
- 软件测试 - 概念篇
- Huawei Hongmeng OS, is it OK?
- Matplotlib double Y axis + adjust legend position
- all3dp. All Arduino projects in com website (2022.7.1)
- Zzuli:1065 count the number of numeric characters
- Zzuli:1068 binary number
- STC8H8K系列汇编和C51实战——按键允许按键计数(利用下降沿中断控制)
- servlet的web.xml配置详解(3.0)
- vite如何兼容低版本浏览器
猜你喜欢
【论文翻译】GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond
15 C language advanced dynamic memory management
深度学习分类网络 -- AlexNet
神机百炼3.53-Kruskal
[personal test] copy and paste code between VirtualBox virtual machine and local
CNN可视化技术 -- CAM & Grad-CAM详解及pytorch简洁实现
“简单”的无限魔方
[C language] simple implementation of mine sweeping game
软件测试基础篇
"Simple" infinite magic cube
随机推荐
51单片机——ADC讲解(A/D转换、D/A转换)
STC8H8K系列汇编和C51实战——数码管显示ADC、按键串口回复按键号与ADC数值
软件测试答疑篇
Redis key value database [seckill]
[C language] screening method for prime numbers
【論文翻譯】GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond
[Chongqing Guangdong education] selected reading reference materials of British and American literature of Nanyang Normal University
php继承(extends)
Some experience of exercise and fitness
Cambrian was reduced by Paleozoic venture capital and Zhike shengxun: a total of more than 700million cash
神机百炼3.52-Prim
How to change the IP address of computer mobile phone simulator
Web页面用户分步操作引导插件driver.js
mysql的约束总结
How to write good code - Defensive Programming Guide
Stc8h8k series assembly and C51 actual combat - keys allow key counting (using falling edge interrupt control)
3D printer G code command: complete list and tutorial
Lantern Festival gift - plant vs zombie game (realized by Matlab)
文件包含漏洞(一)
[personal test] copy and paste code between VirtualBox virtual machine and local