RasMason
RasMason

Reputation: 2212

comparing JWT expired time to now, always false, node Angular 4 app

I'm signing a JWT when a user logs in, from a node server, using express, sending to Angular client side.

The problem I'm having is when checking if the expire time, is more than the current time, is always false

Server side:

var jwt = require('jsonwebtoken');

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

Client side:

  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);
  }

When the token is decoded the exp claim returns 1509551526 (At that time)

I compare them using the function below:

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

current_time returns 1509544328.137 (At that time) so:

if (1509544328.137 > 1509551526)

Or

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

I have logged the typeof for both variables and they are numbers

Upvotes: 1

Views: 3646

Answers (3)

Ricardo Saracino
Ricardo Saracino

Reputation: 1420

I would just compare the exp to the current time an save yourself the hassle of messing with dates.

this._expiration = null;

if (token) {
  try {
    const jwt = jwt_decode(token) as any;
    this._expiration = jwt?.exp ?? null;
  } catch (e) {
    console.error('Error decoding jwt');
  }
}


if (this._expiration === null || this._expiration < ((new Date()).getTime()/1000))
{
  this.signOut();
  return false;
}

return true;

Upvotes: 0

Patel Vaghesh
Patel Vaghesh

Reputation: 73

To Compare Current Time with Expire Time in 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');
}

'''

Upvotes: 1

Milo
Milo

Reputation: 3453

Try using + operator in the comparison:

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

Or make sure you are using .getTime() with the Date objects.

Those conditions you posted should equate to false; first value is less than the second. Or is the problem you're not getting the correct expiry time?

if (1509544328.137 > 1509551526)

Upvotes: 3

Related Questions