**
JJWT工具类
**
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.7.0</version>
</dependency>
package com.bc.Util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.SneakyThrows;
import org.junit.Test;
import java.security.MessageDigest;
import java.util.Date;
/**
* JWT工具类
*
* @author bool
*/
public class JwtUtils {
/**
* 有效期24小时
*/
private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
/**
* 使用固定的解密秘钥
*/
private static final String SECRET = "PisyGFJhgzrctMOofvaHLuiNFOmktedw";
/**
* 校验是否正确
*
* @param token
* @param
* @return
*/
public static boolean verify(String token) {
try {
// 根据密码生成JWT效验器
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.build();
// 效验TOKEN
verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}
/**
* 从Token中解密数据
*
* @param token
* @return
*/
public static String getInfo(String token, String name) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim(name).asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 生成JWT Token字符串
*
* @param username
* @return
*/
public static String sign(String username, String id) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
// 附带username信息
return JWT.create()
.withClaim("username", username)
.withClaim("id", id)
.withExpiresAt(date).sign(algorithm);
}
@SneakyThrows
@Test
public void fangda() {
//生成token签名
String token = sign("111", "222");
//验证是否过期
System.out.println(verify(token));
//获取信息
System.out.println(getInfo(token, "username"));
System.out.println(getInfo(token, "id"));
Thread.sleep(5000);
System.out.println(verify(token));
}
}
}