我正在寻找一种基于过期令牌的真实性更新jwt令牌的机制。 这是我的尝试
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import constants.AppConstants;
import java.io.UnsupportedEncodingException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class JwtUtil {
private static JWTVerifier verifier;
private static String secret = AppConstants.JWT_KEY;
static {
Algorithm algorithm = null;
try {
algorithm = Algorithm.HMAC256(secret);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
verifier = JWT.require(algorithm)
.withIssuer("Issuer")
.build();
}
public static String getSignedToken(Long userId) {
Algorithm algorithm = null;
try {
algorithm = Algorithm.HMAC256(secret);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return e.getMessage();
}
return JWT.create()
.withIssuer("Issuer")
.withIssuedAt(Date.from(
ZonedDateTime.now(ZoneId.systemDefault()).toInstant()
))
.withClaim("userId", userId)
.withExpiresAt(Date.from(ZonedDateTime.now(
ZoneId.systemDefault()).plusMinutes(10).toInstant()
))
.sign(algorithm);
}
public static String renewSignedToken(String oldToken) throws JWTVerificationException{
DecodedJWT jwt = JWT.decode(oldToken);
Long userId = jwt.getClaim("userId").asLong();
return getSignedToken(userId);
}
public static Long verifyToken(String token) throws TokenExpiredException{
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("userId").asLong();
}
}
正如您在验证部分renewSignedToken中看到的那样,我能够获得有效载荷,但是我想添加检查令牌是否具有有效的签名并且声明没有更改。