【问题标题】:How to extract JWT Expiry date without resource server?如何在没有资源服务器的情况下提取 JWT 到期日期?
【发布时间】:2019-12-28 23:26:42
【问题描述】:

我有一个单页应用程序,它从 AWS cognito 请求 JWT 以访问资源服务器中受保护的资源。但是,当 JWT 过期时,我想以编程方式刷新它。为此,我需要知道令牌是否过期以触发刷新。这是下面的 JWT。

{
      "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
      "aud": "xxxxxxxxxxxxexample",
      "email_verified": true,
      "token_use": "id",
      "auth_time": 1500009400,
      "iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example",
      "cognito:username": "janedoe",
      "exp": 1500013000, // <---- this is what we want
      "given_name": "Jane",
      "iat": 1500009400,
      "email": "janedoe@example.com"
      }

然而,我的困境是我不知道如何检查它何时过期而不将其发送到资源服务器进行验证,并且我无法在前端进行验证,因为这会暴露应用程序的秘密。我认为exp 变量可能是从特定日期开始的毫秒数,但我不确定(谷歌上没有任何证据证实这一点)。

所以我想问一下,如何从exp 变量中确定到期日期?

【问题讨论】:

  • 什么是SPA? ..
  • 单页应用程序(我会更新问题以反映这一点)
  • 在资源服务器上,你是否应用了任何机制来响应过期令牌?如果不是,您必须在服务器上执行此操作。然后根据服务器的响应,您将在前端刷新它。在 Angular 中,您可以在拦截器中执行此操作。

标签: authentication jwt amazon-cognito


【解决方案1】:

exp 声明确实是您正在寻找的。它是expiration time,编码为numeric value,代表the number of seconds since 1970-01-01 00:00 UTC(也称为UNIX Epoch 时间)

如果您将鼠标指向数字时间戳,您可以在 https://jwt.io/ 上检查您的令牌并查看转换后的时间戳。

这是一个小的 js sn-p,它演示了如何计算剩余时间:

// exp = 2019-09-01 00:00 UTC
var exp = 1567296000
var currentTimeSeconds = Math.round(+new Date()/1000);
console.log(currentTimeSeconds)
var remainingSeconds = exp - currentTimeSeconds
console.log(remainingSeconds + " seconds remaining")

这里是如何将其转换为日期类型,以当地时间输出:

// exp = 2019-09-01 00:00 UTC
var exp = 1567296000

var expDate = new Date(exp*1000);

var expYear =  expDate.getYear() + 1900
var expMonth = expDate.getMonth() + 1
var expDay = expDate.getDate() 
var expHours = "0" + expDate.getHours()
var expMinutes = "0" + expDate.getMinutes()
var expSeconds = "0" + expDate.getSeconds()
var expFormatted = expYear + "-" + expMonth + "-" + expDay + " " + expHours.substr(-2) + ':' + expMinutes.substr(-2) + ':' + expSeconds.substr(-2);
console.log(expFormatted)

【讨论】:

    【解决方案2】:

    Cognito 在其库中提供了一些标准会话验证。

    如果您使用的是 JavaScript,则可以使用获取一组有效的令牌

    CognitoUser.getSession((err, session) => {
      ... 
    })
    

    这将检查 id 和访问令牌,如果其中任何一个已过期,将使用刷新令牌检索更新的令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2018-07-19
      • 1970-01-01
      • 2015-11-17
      • 2023-03-25
      • 2018-12-07
      相关资源
      最近更新 更多