Jwt工具类
This commit is contained in:
@@ -41,7 +41,7 @@ public interface PatternRegex {
|
||||
/**
|
||||
* 登录名只能输入3-16位的英文字母或数字
|
||||
*/
|
||||
String LOGIN_NAME_REGEX = "^[a-zA-Z_.]{1}[a-zA-Z0-9_.]{2,15}$";
|
||||
String LOGIN_NAME_REGEX = "^[a-zA-Z]{1}[a-zA-Z0-9]{2,15}$";
|
||||
|
||||
/**
|
||||
* 手机号必须有11位,并且为数字,是正常的手机·号码开头
|
||||
|
||||
@@ -17,7 +17,7 @@ public interface SecurityConstants {
|
||||
/**
|
||||
* JWT令牌前缀
|
||||
*/
|
||||
String AUTHORIZATION_PREFIX = "bearer ";
|
||||
String AUTHORIZATION_PREFIX = "Bearer ";
|
||||
|
||||
/**
|
||||
* Basic认证前缀
|
||||
|
||||
64
njcn-common/src/main/java/com/njcn/common/utils/JwtUtil.java
Normal file
64
njcn-common/src/main/java/com/njcn/common/utils/JwtUtil.java
Normal file
@@ -0,0 +1,64 @@
|
||||
package com.njcn.common.utils;
|
||||
|
||||
import cn.hutool.jwt.JWT;
|
||||
import cn.hutool.jwt.JWTUtil;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author caozehui
|
||||
* @data 2024/11/18
|
||||
*/
|
||||
public class JwtUtil {
|
||||
/**
|
||||
* 过期时间(单位:秒)
|
||||
*/
|
||||
public static final int ACCESS_EXPIRE = 60 * 60 * 24;
|
||||
|
||||
private final static String SECRET = "da3f9a7ad5a7d9dd5a7d9dd5a7d9d";
|
||||
|
||||
/**
|
||||
* jwt主题
|
||||
*/
|
||||
private final static String SUBJECT = "NJCN_PQS9100";
|
||||
|
||||
/**
|
||||
* jwt签发者
|
||||
*/
|
||||
private final static String JWT_ISS = "NJCN";
|
||||
|
||||
public static String generateToken(String userId) {
|
||||
Map<String, Object> headers = new HashMap<>();
|
||||
headers.put("typ", "JWT");
|
||||
headers.put("alg", "HS256");
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("userId", userId);
|
||||
payload.put("exp", Instant.now().plusSeconds(ACCESS_EXPIRE).getEpochSecond());
|
||||
payload.put("sub", SUBJECT);
|
||||
payload.put("iss", JWT_ISS);
|
||||
payload.put("iat", Instant.now().getEpochSecond());
|
||||
return JWTUtil.createToken(headers, payload, SECRET.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Map<String, Object> parseToken(String token) {
|
||||
return JWTUtil.parseToken(token)
|
||||
.setKey(SECRET.getBytes(StandardCharsets.UTF_8))
|
||||
.getPayload()
|
||||
.getClaimsJson();
|
||||
}
|
||||
|
||||
public static void invalidateToken(String token) {
|
||||
JWT.of(token).setPayload("exp", Instant.now().getEpochSecond());
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String token = generateToken("123456");
|
||||
System.out.println(token);
|
||||
Map<String, Object> payload = parseToken(token);
|
||||
System.out.println(payload);
|
||||
invalidateToken(token);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user