package com.ht.web.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
public class JwtDemo {
public static void main(String[] main) {
try {
//創建加密算法
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
//簽發者
.withIssuer("auth0")
//自定義KV
.withClaim("admin", "jack")
//過期時間,必須大於簽發時間
.withExpiresAt(new Date())
//生效時間,定義在什麼時間之前,該Token都是不可用的
.withNotBefore(new Date())
//簽發時間,一般爲當前時間
.withIssuedAt(new Date())
.sign(algorithm);
System.out.println(token);
} catch (JWTCreationException exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImFkbWluIjoiamFjayIsImlhdCI6MTU4MzkxMjIxOH0.8aTS51RiyNs9lEjLDvSr7SHb_ON2x6E4zeJGWAo_IsI";
try {
//創建加密算法
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
//可以強制判斷token當中是否包含此字段
.withIssuer("auth0")
.withClaim("admin", "jack")
//單位秒: 可以接受過期的時間長度,
//比如過期時間爲15:30:00,可以往後延45秒,那麼過期時間爲15:30:45
.acceptExpiresAt(45)
//單位秒:可以接受提前使用的時間長度,
//比如NotBefore定以爲15:30:00,那麼在到時間之前正常token都不可用
//設置爲60,代表提前一分鐘可以用 那麼token在15:29:00就可以用了
.acceptNotBefore(60)
.build();
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt.getClaim("admin").asString());
System.out.println(jwt.getExpiresAt());
System.out.println(jwt.getIssuedAt());
} catch (JWTVerificationException exception){
//Invalid signature/claims
exception.printStackTrace();
}
}
}