当前位置:网站首页>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 ");
}
边栏推荐
- External interrupts cannot be accessed. Just delete the code and restore it Record this unexpected bug
- Keepalived installation, use and quick start
- Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders
- Zzuli:1066 character classification statistics
- 正则表达式总结
- [personal test] copy and paste code between VirtualBox virtual machine and local
- PHP parent
- "Simple" infinite magic cube
- File contains vulnerabilities (II)
- 神机百炼3.52-Prim
猜你喜欢

TI毫米波雷达学习(一)

keepalived安装使用与快速入门

Minimum value ruler method for the length of continuous subsequences whose sum is not less than s

5g market trend in 2020

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

正则表达式总结

Vscode paste image plugin saves image path settings

Cube magique infini "simple"

Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders

CNN可视化技术 -- CAM & Grad-CAM详解及pytorch简洁实现
随机推荐
软件测试答疑篇
ES6的详细注解
OLED12864 液晶屏
PHP parent
Redis Key-Value数据库【初级】
The Hong Kong Stock Exchange learned from US stocks and pushed spac: the follow-up of many PE companies could not hide the embarrassment of the world's worst stock market
1035 Password
“簡單”的無限魔方
页面打印插件print.js
Common websites for Postgraduates in data mining
1035 Password
Pytorch Chinese document
Typora installation (no need to enter serial number)
Go learning notes integration
Can't the dist packaged by vite be opened directly in the browser
Redis Key-Value数据库 【秒杀】
Vscode paste image plugin saves image path settings
《CGNF: CONDITIONAL GRAPH NEURAL FIELDS》阅读笔记
[personal test] copy and paste code between VirtualBox virtual machine and local
神机百炼3.54-染色法判定二分图