84 lines
2.6 KiB
Java
84 lines
2.6 KiB
Java
//
|
|
// Source code recreated from a .class file by IntelliJ IDEA
|
|
// (powered by FernFlower decompiler)
|
|
//
|
|
|
|
package com.luozhihui.project.util;
|
|
|
|
import com.auth0.jwt.JWT;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.auth0.jwt.exceptions.TokenExpiredException;
|
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
|
import com.auth0.jwt.interfaces.JWTVerifier;
|
|
import com.auth0.jwt.interfaces.Verification;
|
|
import java.util.Date;
|
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
@Component
|
|
@ConfigurationProperties(
|
|
prefix = "jwt"
|
|
)
|
|
public class JwtUtil {
|
|
public static String header;
|
|
public static String tokenPrefix;
|
|
public static String secret;
|
|
public static long expireTime;
|
|
public static final String USER_LOGIN_TOKEN = "token";
|
|
|
|
public JwtUtil() {
|
|
}
|
|
|
|
public void setHeader(String header) {
|
|
JwtUtil.header = header;
|
|
}
|
|
|
|
public void setTokenPrefix(String tokenPrefix) {
|
|
JwtUtil.tokenPrefix = tokenPrefix;
|
|
}
|
|
|
|
public void setSecret(String secret) {
|
|
JwtUtil.secret = secret;
|
|
}
|
|
|
|
public void setExpireTime(int expireTimeInt) {
|
|
expireTime = (long)expireTimeInt;
|
|
}
|
|
|
|
public static String createToken(String sub) {
|
|
return tokenPrefix + JWT.create().withSubject(sub).withExpiresAt(new Date(System.currentTimeMillis() + expireTime)).sign(Algorithm.HMAC512(secret));
|
|
}
|
|
|
|
public static String validateToken(String token) throws Exception {
|
|
try {
|
|
Verification verification = JWT.require(Algorithm.HMAC512(secret));
|
|
JWTVerifier jwtVerifier = verification.build();
|
|
String noPrefixToken = token.replace(tokenPrefix, "");
|
|
DecodedJWT decodedJwt = jwtVerifier.verify(noPrefixToken);
|
|
return decodedJwt != null ? decodedJwt.getSubject() : "";
|
|
} catch (TokenExpiredException var5) {
|
|
TokenExpiredException e = var5;
|
|
e.printStackTrace();
|
|
return "";
|
|
} catch (Exception var6) {
|
|
Exception e = var6;
|
|
e.printStackTrace();
|
|
return "";
|
|
}
|
|
}
|
|
|
|
public static boolean isNeedUpdate(String token) throws Exception {
|
|
Date expiresAt = null;
|
|
|
|
try {
|
|
expiresAt = JWT.require(Algorithm.HMAC512(secret)).build().verify(token.replace(tokenPrefix, "")).getExpiresAt();
|
|
} catch (TokenExpiredException var3) {
|
|
return true;
|
|
} catch (Exception var4) {
|
|
throw new Exception("token 验证失败");
|
|
}
|
|
|
|
return expiresAt.getTime() - System.currentTimeMillis() < expireTime >> 1;
|
|
}
|
|
}
|