express-jwt-authentication-starter icon indicating copy to clipboard operation
express-jwt-authentication-starter copied to clipboard

jwt iat & exp

Open jonnymholt opened this issue 3 years ago • 4 comments

Hi I just wanted to highlight something as well as suggest the fix should it be wanted.

In the issueJWT function in your utils.js file, the payload sets the iat key to Date.now(). This isn't correct as it sets iat to milliseconds representation, rather than seconds. It also creates an issue in that the jwt sign function uses expiresIn '1d'. This in turn is not then set correctly, based upon the iat date being issued in the distant future. It does not seem to generate a jwt that has valid iat or exp claims when you check it on jwt.io, and it doesn't expire the jwt's authorizaton as expected the following day.

The solution is to amend the payload to set the iat to seconds as such:

const payload = {
    sub: _id,
    iat: Math.floor(Date.now() / 1000)
  };

This then sets the iat, and more importantly the exp claims correctly so that the jwt correctly expires as checked by passport.

Hope this helps

jonnymholt avatar Apr 04 '21 21:04 jonnymholt

This is not related to your suggestion.

How could we implement Redis to store RefreshToken from this tutorial?

l2D avatar May 05 '21 23:05 l2D

@jonnymholt Thanks for bringing this up. If you want to submit a pull request I will merge into the main branch :)

zachgoll avatar May 08 '21 21:05 zachgoll

@jonnymholt Thanks for sharing the solution I needed it thanks @zachgoll for everything

Gennaro-Nucaro avatar Oct 15 '21 14:10 Gennaro-Nucaro

You don't need to explicitly include iat. It is added by default when signing the token.

Generated jwts will include an iat (issued at) claim by default unless noTimestamp is specified. If iat is inserted in the payload, it will be used instead of the real timestamp for calculating other things like exp given a timespan in options.expiresIn.

Taken from here: https://www.npmjs.com/package/jsonwebtoken

ivanbacher avatar Sep 05 '23 10:09 ivanbacher