java - 如何确保过期的 JWT 令牌完好无损
问题描述
我正在寻找一种基于过期令牌的真实性来更新 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 中看到的那样,我能够获取有效负载,但我想添加检查令牌是否具有有效签名并且声明未更改。
解决方案
推荐阅读
- javascript - 直接在html中使用ES6模块中定义的函数
- javascript - 富文本编辑器上的粘贴按钮问题
- python - 如何在不同的机器上使用 Django 查询
- c# - 在服务器上构建解决方案时出错
- c# - 如何找出当前会话不保留数据的原因?
- node.js - aws-amplify auth currentSession 不返回当前用户
- react-final-form - 管理多个相关字段的错误状态
- python - 硬币的分水岭分析 - 错误的输出
- postgresql - 如何查看PostgreSQL中的表关系(如果有外键列,主键是什么...)?
- c++ - 从 C++ 函数返回 char*