package com.leng.demo.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.Map;
public class JWTUtil {
/**
* 过期时间6小时
*/
private static final long EXPIRE_TIME = 6 * 60 * 60 * 1000;
/**
* 校验token是否正确
*
* @param token 密钥
* @param secret 用户的密码
* @return 是否正确
*/
public static boolean verify(String token, String username, String secret) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}
/**
* 刷新令牌
*
* @param token 原令牌
* @return 新令牌
*/
public static String refreshToken(String token) {
String refreshedToken = "";
try {
Map<String, Claim> claims = getClaimsFromToken(token);
Claim username = claims.get("username");
String string = username.asString();
System.out.println(string);
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private static Map<String, Claim> getClaimsFromToken(String token) throws Exception {
Map<String, Claim> claims = null;
try {
DecodedJWT decode = JWT.decode(token);
claims = decode.getClaims();
String signature = decode.getSignature();
System.out.println(signature);
} catch (Exception e) {
new Throwable(e);
}
return claims;
}
/**
* 获得token中的信息无需secret解密也能获得
*
* @return token中包含的用户名
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 生成签名,2min后过期
*
* @param username 用户名
* @param secret 用户的密码
* @return 加密的token
*/
public static String sign(String username, String secret) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
System.out.println(algorithm);
// 附带username信息s
return JWT.create()
.withClaim("username", username)
.withExpiresAt(date)
.sign(algorithm);
}
/**
* 判断过期
*
* @param token
* @return
*/
public static boolean isExpire(String token) {
DecodedJWT jwt = JWT.decode(token);
return System.currentTimeMillis() > jwt.getExpiresAt().getTime();
}
public static void main(String[] args) {
String sign = sign("ange", "123456");
System.out.println(sign);
}
}
JWT工具类
于 2023-05-04 16:50:42 首次发布