使用JWT
引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
生成token
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND, 90);
String token = JWT.create()
.withClaim("username", "张三")
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("Q2W#E$RW"));
System.out.println(token);
根据令牌和签名解析数据
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("token!Q2W#E$RW")).build();
DecodedJWT decodedJWT = jwtVerifier.verify(token);
System.out.println(decodedJWT.getClaim("username").asString());
System.out.println("过期时间: "+decodedJWT.getExpiresAt());
常见异常信息
SignatureVerificationException
TokenExpiredException
AlgorithmMismatchException
InvalidClaimException
|