当前位置:网站首页>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 ");
}
边栏推荐
- PHP extensions
- Zzuli:1069 learn from classmate Z
- Go learning notes integration
- [C language] screening method for prime numbers
- [paper translation] gcnet: non local networks meet squeeze exception networks and beyond
- RGB infinite cube (advanced version)
- JWT工具类
- PHP gets CPU usage, hard disk usage, and memory usage
- Web页面用户分步操作引导插件driver.js
- 文件包含漏洞(二)
猜你喜欢
vite如何兼容低版本浏览器
Vscode paste image plugin saves image path settings
死磕大屏UI,FineReport开发日记
3D 打印机 G 代码命令:完整列表和教程
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
500. 键盘行
[C language] simple implementation of mine sweeping game
测试 - 用例篇
Can't the dist packaged by vite be opened directly in the browser
Eco express micro engine system has supported one click deployment to cloud hosting
随机推荐
页面打印插件print.js
5g market trend in 2020
all3dp. All Arduino projects in com website (2022.7.1)
软件测试基础篇
PHP development and testing WebService (soap) -win
ES6的详细注解
vite如何兼容低版本浏览器
Grbl software: basic knowledge of simple explanation
492.构造矩形
Cube magique infini "simple"
How vite is compatible with lower version browsers
3D printer G code command: complete list and tutorial
OLED12864 液晶屏
js判断移动端还是pc端
Linkage between esp8266 and stc8h8k single chip microcomputer - Weather Clock
1035 Password
Vscode paste image plugin saves image path settings
Yyds dry inventory what is test driven development
“簡單”的無限魔方
1035 Password