1.首先引入maven依赖
<!--JWT依赖-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<!--json转换依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
2.写一个JWT的工具类
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.qcby.xmfs.boot.entity.User;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
@Slf4j
public class JwtUtilBak {
//过期时间 2min
private static final int EXPIRE_TIME = 2;
//私钥 自定义
private static final String TOKEN_SECRET = "privateKey";
// 普通常量
private static final String CLAIM_USER = "claimUser";
public static String createToken(User user) {
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.MINUTE,EXPIRE_TIME);
Date expiresDate = nowTime.getTime();
String userJson = JSON.toJSONString(user);
return JWT.create()
.withAudience(user.getId()+"") //签发对象
.withIssuedAt(new Date()) //发行时间
.withExpiresAt(expiresDate) //有效时间
// 存储用户信息 => json转化 ,序列化
.withClaim(CLAIM_USER,userJson) //载荷 => 附带信息:比如用户信息
.sign(Algorithm.HMAC256(user.getId()+TOKEN_SECRET)); //加密
}
/**
* 检验合法性,其中secret参数就应该传入的是签发对象 用户的id
* @param token
*/
public static boolean verifyToken(String token, String secret) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret+TOKEN_SECRET)).build();
verifier.verify(token);
} catch (Exception e) {
log.error(e.getMessage(),e);
//效验失败
//自定义的一个异常
return false;
}
return true;
}
/**
* 获取签发对象 根据用户ID验证
*/
public static String getAudience(String token) {
String audience = null;
try {
audience = JWT.decode(token).getAudience().get(0);
} catch (Exception j) {
log.error(j.getMessage(),j);
return null;
}
return audience;
}
/**
* 获取载荷中用户信息
* @param token
* @return
*/
public static User getUser(String token) {
User user = null;
try {
String userJson = JWT.decode(token).getClaim(CLAIM_USER).asString();
user = JSON.parseObject(userJson,User.class);
} catch (JWTDecodeException j) {
log.error(j.getMessage(),j);
return null;
}
return user;
}
}