use of com.auth0.jwt.impl.NullClaim in project yyl_example by Relucent.
the class JwtDemo method main.
public static void main(String[] args) throws Exception {
long currentMillis = System.currentTimeMillis();
// JWT 生存时间(5秒)
long ttl = 5000;
// 生成JWT的时间
Date iat = new Date(currentMillis);
// 生成JWT失效时间
Date exp = new Date(currentMillis + ttl);
// 签名秘钥
String secret = "key";
// 签发人
String issuer = "root";
// 算法
Algorithm algorithm = Algorithm.HMAC256(secret);
// 本地的密码解码
JWTCreator.Builder builder = JWT.create();
// 签发时间
builder.withIssuedAt(iat);
// 签发人
builder.withIssuer(issuer);
// 过期时间
builder.withExpiresAt(exp);
// 主题
builder.withClaim("subject", "MySubject");
String token = builder.sign(algorithm);
System.out.println(token);
// 解密
JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
Map<String, Claim> claims = jwt.getClaims();
NullClaim nullClaim = new NullClaim();
System.out.println(claims.getOrDefault("subject", nullClaim).asString());
// 等待5秒
System.out.println("Wait 5 seconds!");
Thread.sleep(5000);
try {
// 这时候Token已经超时了,会抛出异常
verifier.verify(token);
} catch (JWTVerificationException e) {
System.err.println(e);
}
}
Aggregations