Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  22] [ 6]  / answers: 1 / hits: 28752  / 9 Years ago, sat, october 24, 2015, 12:00:00

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.)


More From » node.js

 Answers
4

Based on what Krzysztof Sztompka posted, I could get the Ext to show the correct expiry date. (my original requirement was for 1 hour in the future)



To keep track of the change vs previous mistakes, I won't update the code above, so here is what I changed:



var d = new Date();

var calculatedExpiresIn = (((d.getTime()) + (60 * 60 * 1000)) - (d.getTime() - d.getMilliseconds()) / 1000);

var token = jwt.sign({id: user._id}, configGeneral.JWT, { expiresIn: calculatedExpiresIn });


The console.log's will now show that the Ext is as I wanted it, now + 1 hour.



To get the Iat to show the correct date (after setting it in the sign function and then sanity checking it in the decode function), I had to set it as part of the payload. I got my answer here



So finally to get the Iat to show correctly I added it to the payload as shown here:



var token = jwt.sign({id: user._id, iat: (new Date().getTime())}, configGeneral.JWT, { expiresIn: calculatedExpiresIn });


This gives an output of:



{ id: '56253091fe0397c80133f3e4',
iat: 1445763099706,
exp: 1445766699705 }
Sun Oct 25 2015 11:51:39 GMT+0200 (South Africa Standard Time)
Sun Oct 25 2015 10:51:39 GMT+0200 (South Africa Standard Time)


This is the unencoded JWT which I will passed back to the users when they have signed in successfully and will allow me to check whether the JWT they have to pass as every future request is still valid and hasn't expired yet.


[#64613] Thursday, October 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bretd

Total Points: 6
Total Questions: 100
Total Answers: 97

Location: England
Member since Sun, May 21, 2023
1 Year ago
;