package com.hxzkmonitor.util;
|
|
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.JwtBuilder;
|
import io.jsonwebtoken.Jwts;
|
import io.jsonwebtoken.SignatureAlgorithm;
|
import org.bouncycastle.util.encoders.Base64;
|
|
import javax.crypto.SecretKey;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.util.Date;
|
|
/**
|
*
|
* jwt工具类
|
*
|
**/
|
public class JwtUtil {
|
|
/**
|
* 签发JWT
|
* @param subject 可以是JSON数据 尽可能少
|
* @param ttlMillis token有效时间
|
* @return String
|
*
|
*/
|
public static String createJWT(String subject, long ttlMillis) {
|
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
|
long nowMillis = System.currentTimeMillis();
|
Date now = new Date(nowMillis);
|
SecretKey secretKey = generalKey();
|
JwtBuilder builder = Jwts.builder()
|
// .setId(IdUtils.simpleUUID()) //唯一性
|
.setSubject(subject) // 主题
|
.setIssuer("admin") // 签发者
|
.setIssuedAt(now) // 签发时间
|
.signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
|
if (ttlMillis >= 0) {
|
long expMillis = nowMillis + ttlMillis;
|
Date expDate = new Date(expMillis);
|
builder.setExpiration(expDate); // 过期时间
|
}
|
return builder.compact();
|
}
|
|
/**
|
* 密钥
|
* @return
|
*/
|
public static SecretKey generalKey() {
|
byte[] encodedKey = Base64.decode("xxxxxxxx"); //自定义密钥, 不能外泄
|
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
|
return key;
|
}
|
|
/**
|
*
|
* 解析JWT字符串
|
* @param jwt
|
* @return
|
* @throws Exception
|
*/
|
public static Claims parseJWT(String jwt) throws Exception {
|
SecretKey secretKey = generalKey();
|
return Jwts.parser()
|
.setSigningKey(secretKey)
|
.parseClaimsJws(jwt)
|
.getBody();
|
}
|
|
/**
|
* 获取用户
|
* @param token
|
* @return
|
* @throws Exception
|
*/
|
// public synchronized static WxUser getUser(String token) {
|
// WxUser user = null;
|
// String subject = null;
|
// try {
|
// subject = parseJWT(token).getSubject();
|
// } catch (Exception e) {
|
// e.printStackTrace();
|
// }
|
// WxUser userModel = JsonListUtil.jsonToBean(subject, WxUser.class);
|
// if (ObjectUtil.isNotEmpty(userModel)) {
|
// user = SpringUtil.getBean(WxUserMapper.class).selectWxUserById(userModel.getId());
|
// }
|
// return user;
|
// }
|
}
|