我有以下实用程序类,但每当我通过验证方法检查过期令牌时,它都不会抛出JWtVerificationException
。
public class Token {
private static String SECRET = "c3bff416-993f-4760-9275-132b00256944";
public static String get(String name, String value) throws UnsupportedEncodingException {
return JWT.create()
.withIssuer("auth0")
.withClaim(name, value)
.withClaim("random", String.valueOf(UUID.randomUUID()))
.withExpiresAt(new Date(System.currentTimeMillis() + (4 * 60 * 60 * 1000)))
.sign(Algorithm.HMAC256(Token.SECRET));
}
public static DecodedJWT verify(String token) throws JWTVerificationException, UnsupportedEncodingException {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Token.SECRET))
.withIssuer("auth0")
.acceptExpiresAt(4)
.build();
return verifier.verify(token);
}
}
根据网站https://github.com/auth0/java-jwt
验证令牌时,时间验证会自动进行,当值无效时会导致
JWTVerificationException
被抛出。
修改:
客户每5分钟更新一次令牌的情况,是继续工作还是应该增加几秒钟以适应任何网络延迟?
创建
.withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000))) // 5 minutes
验证
.acceptExpiresAt(5 * 60) // accept expiry of 5 minutes
答案 0 :(得分:1)
JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + (5 * 60 * 1000)))
表示您将创建一个令牌,该令牌将在5分钟后过期。看起来不错。
JWT.require(xxx).acceptExpiresAt(5 * 60)
表示您将接受5分钟前已过期的令牌。即使考虑到网络延迟,5分钟的回旋时间仍然太长。应该在几秒钟内。
答案 1 :(得分:0)
If the token has an invalid signature or the Claim requirement is not met, a JWTVerificationException
will raise.
When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException
being throw when the values are invalid. If any of the previous fields are missing they will not be considered in this validation.
答案 2 :(得分:0)
验证令牌时只需添加单独的catch块
try {
DecodedJWT decodedJWT = Token.verify();
Map claims = decodedJWT.getClaims();
} catch (TokenExpiredException e) {
// Token expired
} catch (JWTVerificationException e) {
// Token validation error
}