【问题标题】:How to check if a JWT Token has expired without throw exceptions?如何检查 JWT 令牌是否已过期而没有抛出异常?
【发布时间】:2021-06-07 12:14:27
【问题描述】:

我正在开发一个 Java 应用程序(使用 Spring Boot),我需要一些帮助: 此应用程序接收我在一个方法中处理的 JWT 令牌 作为输入。目前的方法如下:

private UsernamePasswordAuthenticationToken myMethod(HttpServletRequest request) {
    
    // Code that gets the 'token' String

    try{
    
    Map<String, String> registry = ((Map<String, String>) (token.getBody().get("registry")));
    String sub = ((String) (parsedToken.getBody().get("sub")));


    UsernamePasswordAuthenticationToken finalToken = new UsernamePasswordAuthenticationToken(sub, null, null);
                            
            
    return finalToken; 

            
    } catch (ExpiredJwtException exception) { // Only here I have the certainty that the token has expired!
            // Code that handles the exception
    }

}

但是,我需要实现一个逻辑,该逻辑必须在多个地方检查获得的令牌是否已过期,无需每次都运行此方法。我必须知道token 是否已过期的唯一方法是ExpiredJwtException 引发的异常。

有没有办法知道令牌是否已过期而没有经过捕获的异常?例如,如果有一个具有.isExpired 属性或类似属性的“令牌”类,这将非常有用。

我不想处理异常,因为这意味着每次我需要检查令牌是否已过期时,我总是依赖于 try 块的(长)代码,而且我不想这样。

【问题讨论】:

  • 我相信我已经编写了所有可能的代码来说明问题
  • 还不错

标签: java spring string jwt token


【解决方案1】:

这可以通过使用声明来实现。下面的示例代码可以提供帮助。

// Get Expiration and compare it with new Date()

public boolean isTokenExpired(String token) {
    return extractExpiration(token).before(new Date());
}


public Date extractExpiration(String token) {
    return extractClaim(token, Claims::getExpiration);
}


public <T> T extractClaim(String token , Function<Claims, T> claimResolver) {
    final Claims claim= extractAllClaims(token);
    return claimResolver.apply(claim);
}


private Claims extractAllClaims(String token) {
    return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}

【讨论】:

    【解决方案2】:

    如果您使用不同的 JWT 库,您可以轻松地做到这一点。 auth0 JWT library 具有解析和可选验证令牌的方法:

    import com.auth0.jwt.JWT;
    import com.auth0.jwt.exceptions.JWTDecodeException;
    import com.auth0.jwt.interfaces.DecodedJWT;
    
    
    DecodedJWT jwt = JWT.decode(token);
    if( jwt.getExpiresAt().before(new Date())) {
        System.out.println("token is expired");
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 2018-06-19
      • 2016-08-16
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      相关资源
      最近更新 更多