使用JWT
引入依赖
com.auth0
java-jwt
3.4.0
生成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();
//校对token
DecodedJWT decodedJWT = jwtVerifier.verify(token);
//获取携带的内容
System.out.println(decodedJWT.getClaim("username").asString());
//过期时间
System.out.println("过期时间: "+decodedJWT.getExpiresAt());
常见异常信息
//签名不一致异常
SignatureVerificationException
//令牌过期异常
TokenExpiredException
//算法不匹配异常
AlgorithmMismatchException
//失效的payload异常
InvalidClaimException