当前位置:网站首页>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
- [golang syntax] be careful with the copy of slices
- 脑与认知神经科学Matlab Psytoolbox认知科学实验设计——实验设计四
- STC8H8K系列汇编和C51实战——数码管显示ADC、按键串口回复按键号与ADC数值
- ESP8266与STC8H8K单片机联动——天气时钟
- Stick to the big screen UI, finereport development diary
- 软件测试 - 概念篇
- 页面打印插件print.js
- memcached安装
- [Chongqing Guangdong education] selected reading reference materials of British and American literature of Nanyang Normal University
猜你喜欢

Stick to the big screen UI, finereport development diary

如何写出好代码 — 防御式编程指南

MySQL transaction and isolation level

PHP 开发与测试 Webservice(SOAP)-Win

Thunder on the ground! Another domestic 5g chip comes out: surpass Huawei and lead the world in performance?

Software testing - concept

Grbl software: basic knowledge of simple explanation

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

Balsamiq wireframes free installation

DRM display framework as I understand it
随机推荐
Addchild() and addattribute() functions in PHP
Fundamentals of software testing
Huawei Hongmeng OS, is it OK?
c语言中的几个关键字
Technologists talk about open source: This is not just using love to generate electricity
格式校验js
"Simple" infinite magic cube
Zzuli:1066 character classification statistics
神机百炼3.52-Prim
Several keywords in C language
MUI底部导航的样式修改
Practice C language advanced address book design
[paper translation] gcnet: non local networks meet squeeze exception networks and beyond
PHP array to XML
3D printer G code command: complete list and tutorial
Zzuli:1065 count the number of numeric characters
Lantern Festival gift - plant vs zombie game (realized by Matlab)
Redis Key-Value数据库 【高级】
Stc8h8k series assembly and C51 actual combat - digital display ADC, key serial port reply key number and ADC value
mysql事务和隔离级别