在pom文件中加入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
构建JWT工具类
@Component
public class JWTUtil {
private static final Long EXPIRATION_TIME = 60*60*1000 * 2L; //有效期默认两个小时
private static final String SECRET = "qianrentao"; //秘钥
public static String getToken(String name){
String token = "";
Long time = new Date().getTime() + EXPIRATION_TIME;
try {
token = JWT.create()
.withExpiresAt(new Date(time))
.withClaim("account",name)
.sign(Algorithm.HMAC256(SECRET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return token;
}
public static void checkToken(String token) throws Exception{
DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
System.out.println(verify.getClaim("account").asString());
}
}
本文介绍了如何在Maven项目中添加com.auth0的java-jwt库依赖,并详细展示了如何构建一个使用HMAC256算法的JWT工具类,包括生成和验证JWT的过程。
651

被折叠的 条评论
为什么被折叠?



