org.macrocloud.kernel.auth.utils.JwtUtil Maven / Gradle / Ivy
package org.macrocloud.kernel.auth.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.macrocloud.kernel.auth.exception.SecureException;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
/**
* Jwt工具类
*/
public class JwtUtil {
/**
* token基础配置
*/
public static String BEARER = "bearer";
public static Integer AUTH_LENGTH = 7;
/**
* token保存至redis的key
*/
public static final String TOKEN_CACHE = "macrocloud:token";
public static final String TOKEN_KEY = "token:state:";
/**
* refreshToken 保存至redis的key
*/
public static final String REFRESH_TOKEN_CACHE = "macrocloud:refreshToken";
public static final String REFRESH_TOKEN_KEY = "refreshToken:state:";
/**
* token签名
*/
private static String signKey = "macrocloudisapoweddsdsdsfsdffffffffffssssssssrfulmicroservicearchitectureupgradedandoptimizedfromacommercialaaaproject";
/**
* 签名加密
*/
public static String getBase64Security() {
return Base64.getEncoder().encodeToString(signKey.getBytes(StandardCharsets.UTF_8));
}
/**
* 获取请求传递的token串
*
* @param auth token
* @return String
*/
public static String getToken(String auth) {
if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
String headStr = auth.substring(0, 6).toLowerCase();
if (headStr.compareTo(BEARER) == 0) {
auth = auth.substring(7);
}
return auth;
}
return null;
}
/**
* 解析jsonWebToken
*
* @param jsonWebToken token串
* @return Claims
*/
public static Claims parseJWT(String jsonWebToken) {
try {
return Jwts.parserBuilder()
.setSigningKey(Base64.getDecoder().decode(getBase64Security())).build()
.parseClaimsJws(jsonWebToken).getBody();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static Boolean isTokenExpired(String jsonWebToken) {
Claims claims = parseJWT(jsonWebToken);
Date expiration = claims.getExpiration();
//和当前时间进行对比来判断是否过期
return new Date(System.currentTimeMillis()).after(expiration);
}
}