I am a bit stumped by this one. I am trying to set up a valid JWT. I am using node.js with the jsonwebtoken middleware. I have followed the documentation located on the repo (located here), but I keep getting the wrong Exp and Iat. Obviously I would like to get this right so that I don't allow JWT's which has expired.
As a test I have the following code:
var token = jwt.sign({"id": user._id}, configGeneral.JWT, { expiresIn: '1h' });
var decoded = jwt.decode(token, configGeneral.JWT);
var d1 = new Date(decoded.exp);
var d2 = new Date(decoded.iat);
console.log(decoded);
console.log(d1);
console.log(d2);
The output of this is:
{ id: '56253091fe0397c80133f3e4',
iat: 1445714161,
exp: 1445717761 }
Sat Jan 17 1970 19:35:17 GMT+0200 (South Africa Standard Time)
Sat Jan 17 1970 19:35:14 GMT+0200 (South Africa Standard Time)
How do I get the timestamp to not reflect the javascript epoch, but rather the time 1 hour from now? (for both the iat and exp.)
iat" (Issued At) Claim The "iat" (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value.
For Invalid JWT Signature, check if your service account key has expired. Go to your APIs & Services to add a new key if it has.
You can pass the noTimestamp option, which will prevent adding iat . Something like this should work.
This error occurs if the JSON Web Token (JWT) specified in the <Source> element of the Decode JWT policy is malformed, invalid or otherwise not decodable. A properly structured JWT should contain a header, payload and signature in the following format: header. payload.
This:
new Date().getTime()
give you time in miliseconds. But time in jwt token (iat, exp) is in seconds, therefore we have to divide result by 1000.
var actualTimeInSeconds = new Date().getTime()/1000;
How to get some time in seconds from now:
(new Date().getTime() + someTimeInSeconds * 1000)/1000
If you need 1 hour from now:
(new Date().getTime() + 60 * 60 * 1000)/1000
because 1h = 60min * 60 s
And at this moment you have time in seconds from jwt token and calculated time in seconds. You should only compare this values.
Precisely in your situation you should compare jwt token time with your actual time in seconds. If jwt token expiration time is greater then actual time it means that it is still valid. From docs of jwt token:
The processing of the exp claim requires that the current date/time MUST be before the expiration date/time listed in the exp claim.
To get coorect date from iat, multiply value by 1000 and add to new Date constructor:
new Date(iat*1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With