This commit is contained in:
caozehui
2025-02-07 14:27:54 +08:00
parent 9ef0427f54
commit 6a11ebf907
2 changed files with 13 additions and 17 deletions

View File

@@ -67,7 +67,7 @@ public interface SecurityConstants {
String GRANT_TYPE_KEY = "grant_type";
String REFRESH_TOKEN_KEY = "refresh_token";
String REFRESH_TOKEN_KEY = "Refresh-token";
/**
* 黑名单token前缀

View File

@@ -1,7 +1,9 @@
package com.njcn.common.utils;
import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateUnit;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.njcn.common.pojo.constant.SecurityConstants;
@@ -16,9 +18,9 @@ import java.util.Map;
*/
public class JwtUtil {
/**
* 过期时间(单位:秒)
* 一天的秒数(单位:秒)
*/
public static final long ACCESS_EXPIRE = DateUnit.DAY.getMillis() / 1000;
public static final long DAY_SECOND = DateUnit.DAY.getMillis() / 1000;
private final static String SECRET = "da3f9a7ad5a7d9dd5a7d9dd5a7d9d";
@@ -38,7 +40,7 @@ public class JwtUtil {
headers.put("alg", "HS256");
Map<String, Object> payload = new HashMap<>();
payload.put(SecurityConstants.USER_ID, userId);
payload.put("exp", Instant.now().plusSeconds(ACCESS_EXPIRE).getEpochSecond());
payload.put("exp", Instant.now().plusSeconds(DAY_SECOND * 2).getEpochSecond());
payload.put("sub", SUBJECT);
payload.put("iss", JWT_ISS);
payload.put("iat", Instant.now().getEpochSecond());
@@ -50,7 +52,12 @@ public class JwtUtil {
}
public static boolean isExpired(String token) {
return !JWT.of(token).setKey(SECRET.getBytes(StandardCharsets.UTF_8)).validate(0);
JWT jwt = JWT.of(token).setKey(SECRET.getBytes(StandardCharsets.UTF_8));
JWTPayload payload = jwt.getPayload();
NumberWithFormat exp = (NumberWithFormat) payload.getClaim("exp");
long currentTime = Instant.now().getEpochSecond();
return currentTime > exp.longValue();
}
public static Map<String, Object> parseToken(String token) {
@@ -60,20 +67,9 @@ public class JwtUtil {
.getClaimsJson();
}
public static void invalidateToken(String token) {
JWT.of(token).setKey(SECRET.getBytes(StandardCharsets.UTF_8)).setPayload("exp", Instant.now().getEpochSecond());
}
public static String getRefreshToken(String token) {
Map<String, Object> payload = JWTUtil.parseToken(token).getPayload().getClaimsJson();
payload.put("exp", Instant.now().plusSeconds(ACCESS_EXPIRE * 7).getEpochSecond());
payload.put("exp", Instant.now().plusSeconds(DAY_SECOND * 4).getEpochSecond());
return JWTUtil.createToken(payload, SECRET.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) {
String token = getAccessToken("123456");
System.out.println(token);
System.out.println(parseToken(token));
}
}