import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: liyue
* @Date: 2023/04/03/11:34
* @Description:
*/
public class JwtTest {
private static final String secret = "sofhjsje8f7he3$#3%#jesjfsjf";
private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws ParseException {
String token = generateCode("2023-04-03 11:50:00");
System.out.println(token);
analysis(token);
}
public static String generateCode(String expireTime) throws ParseException {
Map<String, Object> map = new HashMap<>();
map.put("typ", "jwt");
map.put("alg", "HS256");
String token = JWT.create()
.withHeader(map)
.withClaim("username", "root")
.withClaim("password", "123456")
.withExpiresAt(simpleDateFormat.parse(expireTime))
.sign(Algorithm.HMAC256(secret)); // 签名secret
return token;
}
public static void analysis(String token) {
// 创建解析对象,使用的算法和secret要与创建token时保持一致
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
// 解析指定的token
DecodedJWT decodedJWT = jwtVerifier.verify(token);
// 获取解析后的token中的payload信息
Date expiresAt = decodedJWT.getExpiresAt();
System.out.println("username:"+decodedJWT.getClaim("username").toString());
System.out.println("password:"+decodedJWT.getClaim("password").toString());
System.out.println("过期时间:"+simpleDateFormat.format(expiresAt));
}
}