package com.mm.util;
|
|
import com.auth0.jwt.JWT;
|
import com.auth0.jwt.algorithms.Algorithm;
|
import com.auth0.jwt.exceptions.JWTDecodeException;
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
|
import java.util.Date;
|
|
/**
|
* @author clown
|
* * @date 2023/11/23
|
*/
|
public class JwTUtil {
|
/**
|
* 从token中解密出用户名
|
*/
|
public static String getUsername(String token) {
|
try {
|
DecodedJWT jwt = JWT.decode(token);
|
return jwt.getClaim("username").asString();
|
} catch (JWTDecodeException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 判断是否过期
|
*/
|
public static boolean isExpired(String token) {
|
DecodedJWT jwt = JWT.decode(token);
|
return jwt.getExpiresAt().before(new Date());
|
}
|
|
/**
|
* 生成签名
|
*/
|
public static String sign(String username, String secret) {
|
Algorithm algorithm = Algorithm.HMAC256(secret);
|
// 30分钟后过期
|
Date date = new Date(System.currentTimeMillis() + 60 * 60 * 1000);
|
// 附带username信息(只要你愿意,可以附带Map、List等)
|
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
|
|
}
|
|
|
}
|