注意引入的依赖的版本,和工具类是否匹配,不然报错
以下token工具类,需要的依赖:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
package com.sangeng.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
/**
* JWT工具类
*/
public class JwtUtil {
//有效期为
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文
public static final String JWT_KEY = "sangeng";
public static String getUUID(){
String token = UUID.randomUUID().toString().replaceAll("-", "");
return token;
}
/**
* 生成jtw
* @param subject token中要存放的数据(json格式)
* @return
*/
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
return builder.compact();
}
/**
* 生成jtw
* @param subject token中要存放的数据(json格式)
* @param ttlMillis token超时时间
* @return
*/
public static String createJWT(String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
return builder.compact();
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("sg") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate);
}
/**
* 创建token
* @param id
* @param subject
* @param ttlMillis
* @return
*/
public static String createJWT(String id, String subject, Long ttlMillis) {
JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
return builder.compact();
}
public static void main(String[] args) throws Exception {
// String jwt = createJWT("2123");
Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyOTY2ZGE3NGYyZGM0ZDAxOGU1OWYwNjBkYmZkMjZhMSIsInN1YiI6IjIiLCJpc3MiOiJzZyIsImlhdCI6MTYzOTk2MjU1MCwiZXhwIjoxNjM5OTY2MTUwfQ.NluqZnyJ0gHz-2wBIari2r3XpPp06UMn4JS2sWHILs0");
String subject = claims.getSubject();
System.out.println(subject);
// System.out.println(claims);
}
/**
* 生成加密后的秘钥 secretKey
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/**
* 解析
*
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}
}
以下工具类都可以,版本号限制不大
public class JwtTokenUtil {
public static final String CLAIM_KEY_USERNAME = "sub";
public static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")//从properties文件里取值
private String secret;
@Value("${jwt.expiration}")//从properties文件里取值
private Long expiration;
//生成token
public String generateToken(User user) {
String originPhoneNum = SecretUtil.desEncrypt(user.getPhoneNum(),"1234567890123456","1234567890123456");
// 准备荷载
Map<String,Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, user.getUsername());
claims.put(CLAIM_KEY_CREATED,new Date());
return generateToken(claims);
}
//根据荷载生成token
private String generateToken(Map<String,Object> claims){
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.ES512,secret)
.compact();
}
//生成token失效时间
private Date generateExpirationDate() {
return new Date(System.currentTimeMillis()+expiration*1000);
}
//检验token
// 根据token获取用户信息,username
public String getUserDetailsFromToken(String token){
String username;
//获取荷载
try{
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
}catch (Exception e){
username=null;
}
return username;
}
// 从token中获取荷载
private Claims getClaimsFromToken(String token) {
Claims claim = null;
try{
claim = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}catch (Exception e){
e.printStackTrace();
}
return claim;
}
// 检验token是否有效
public boolean validateToken(String token, UserDetails userDetails){
// 1、token是否过期
boolean tokenExpired = isTokenExpired(token);
// 2、用户名是否相等
String username = getUserDetailsFromToken(token);
return (username.equals(userDetails.getUsername()) && !tokenExpired);
}
// 判断token是否失效
private boolean isTokenExpired(String token) {
// 获取token失效时间
Date expireDate = getExpiredDateFromToken(token);
// 判断expireDate在当前时间前面,则token失效
return expireDate.before(new Date());
}
// 获取token失效时间
private Date getExpiredDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
// 判断token是否可以被刷新 token 没过期就可以刷新
public boolean canRefreash(String token){
return !isTokenExpired(token);
}
//刷新token 实际只修改过期时间
public String refreashToken(String token){
//获取荷载
Claims claims = getClaimsFromToken(token);
//修改过期时间
claims.put(CLAIM_KEY_CREATED,new Date());
//根据荷载生成token
return generateToken(claims);
}
}