【问题标题】:comparing JWT expired time to now, always false, node Angular 4 app比较 JWT 过期时间到现在,总是错误的,节点 Angular 4 应用程序
【发布时间】:2018-04-13 21:28:44
【问题描述】:

当用户从节点服务器登录时,我正在签署 JWT,使用 express 发送到 Angular 客户端。

我遇到的问题是在检查过期时间是否超过当前时间时,总是错误

服务器端:

var jwt = require('jsonwebtoken');

  const token = jwt.sign({
      'name': admin.name
    }, RSA_PRIVATE_KEY, {
      algorithm: 'RS256',
      expiresIn: 7200,
      subject: adminId
    });

客户端:

  private setSession(authResult) {
    const decoded = jwt_decode(authResult.token)
    const exp = decoded.exp;
    this.username = decoded.name;
    this.adminId = decoded.sub;
     console.log(exp)// returns 1509551526
    localStorage.setItem('id_token', authResult.token);
    localStorage.setItem("expires_at", exp);
  }

当令牌被解码时,exp 声明返回 1509551526(当时)

我使用下面的函数比较它们:

  public isLoggedIn() {
    var current_time = new Date().getTime() / 1000;
    console.log(current_time)
    if (current_time > this.getExpiration()) {
      console.log("Expired!")
    }
  }

current_time 返回 1509544328.137(当时)所以:

if (1509544328.137 > 1509551526)

或者

if (2017-11-01 13:52:08 > 2017-11-01 15:52:06)

我已经记录了两个变量的 typeof,它们都是数字

【问题讨论】:

    标签: node.js angular jwt


    【解决方案1】:

    尝试在比较中使用+ 运算符:

    if (+current_time > +this.getExpiration()) {
      console.log("Expired!")
    }
    

    或者确保您将 .getTime() 与 Date 对象一起使用。

    您发布的那些条件应该等同于false;第一个值小于第二个。还是您没有得到正确的到期时间?

    如果 (1509544328.137 > 1509551526)

    【讨论】:

    • 感谢您的回答 Milo“您发布的那些条件应该等于 false”让我将代码重构为:return current_time
    【解决方案2】:

    在 Node.js 中比较当前时间和过期时间

    Example For OTP Expire time verification '''

    let currentTime = new Date();
    let otpData = await Otp.findOne({otpNumber: req.body.otp, user: user._id});
    if (!otpData) return res.status(400).send('OTP is invalid.');
    
    if (currentTime.getTime() > otpData.expiresAt.getTime()){
        res.send('OTP is expired');
    }
    else{
        otpData.isUsed = true;
        await otpData.save();   
        res.send('OTP Verified');
    }
    

    '''

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2020-12-15
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 2020-07-16
      相关资源
      最近更新 更多