【问题标题】:extract the expiration datetime from jsonwebtoken从 jsonwebtoken 中提取过期日期时间
【发布时间】:2020-02-01 16:32:24
【问题描述】:

要使令牌无效,据我所知存储令牌的最佳方式是数据库的到期日期时间。要验证它,您只需从数据库中选择它,如果它存在,您就知道它已失效。此外,您可以通过数据库中的过期日期时间删除每个过期的令牌。

所以我创建了一个从授权标头中提取令牌的中间件,它应该将令牌和到期日期时间附加到 request 对象。 signOut 路由需要日期时间才能使令牌失效。

  async use(req: any, res: Response, next: NextFunction) {
    try {
      const headers: IncomingHttpHeaders = req.headers;
      const authorization: string = headers.authorization;
      const bearerToken: string[] = authorization.split(' ');
      const token: string = bearerToken[1];

      if (await this.authenticationsRepository.findByEncodedToken(token)) { // invalidated token?
        throw new Error(); // jump to catch
      }

      req.tokenPayload = verifyToken(token); // calls jwt.verify with secret
      next();
    } catch (error) {
      throw new UnauthorizedException();
    }
  }

但是如何从令牌中提取exp 属性来计算到期日期时间?

【问题讨论】:

  • 你能添加一个相关字符串的例子吗?
  • 抱歉relevant strings 是什么意思?你的意思是一个 jwt 示例字符串?
  • headers.authorization 中到底是什么?这个问题听起来主要是关于字符串解析,而不是关于令牌或到期日期。
  • 啊好吧,headers.authorization 只是请求对象的授权标头 :) 但您可以忽略它并从 token 开始。它将包含从标头中提取的令牌字符串

标签: javascript node.js jwt nestjs


【解决方案1】:

为了获得过期日期,您需要解码 jsonwebtoken 并访问它的 exp 密钥,如下所示:

let token = jwt.sign({
    data: 'foobar'
}, 'secret', { expiresIn: '1h' });


var decoded = jwt.decode(token, { complete: true });
console.log(decoded.payload.exp);

在你的情况下,我认为你可以这样做:

req.expirationTime = jwt.decode(token, { complete: true }).payload.exp;

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2020-08-14
    相关资源
    最近更新 更多