7

I sign a JWT (JSON Web Token) with userID and iat (issues at) like so

jwt.encode({sub: user.id, iat: timestamp}, jwtSecret);

When I receive a JWT from the client, I decode it to extract the userID. Do I need to validate the userID by checking its existence in the database every time I need to allow the user to access a secure route (see first example)? Or can I just assume that the user is who she says she is, and allow her to access the secure path?

My feeling is that I need to access the database to validate the user on every request, this would be expensive and defeat the purpose of using a JWT.

quantdaddy
  • 1,375
  • 4
  • 19
  • 29

2 Answers2

6

Your token is signed. If someone changes the token on client side, it would fail validation and the server side framework would reject it. Therefore you can trust your token. Of course, the jwtSecret should be a secret only known by your authentication server and resource server.

  • You generate the token only if you trust the user who requested it.
  • You trust the token as long as it has not expired and can be verified with the secret.
jps
  • 20,041
  • 15
  • 75
  • 79
  • I just made an edit. I'm not sure why an example in passport-jwt package page does database access to verify the user and then call next middleware – quantdaddy Apr 17 '18 at 06:12
  • I don't know why they made this. The point is, you generate the token only if you trust the user who requested it and you trust the token as long as it is not expired and can be verified with the secret. – jps Apr 17 '18 at 06:22
  • I see. I think the database access in the example is just to get other info about the user and is not required for verification. – quantdaddy Apr 17 '18 at 06:23
3

The whole idea of JWT is that can verify the integrity of the claims contained within it. If you can decode successfully the token you can be sure that this token contains information previously encoded by you. For someone to pass malformed data has to also know the secret you use to sign the tokens.

For more information read this.

Alex Michailidis
  • 4,078
  • 1
  • 16
  • 35
  • what's the point of database access in the first example on this page: https://www.npmjs.com/package/passport-jwt – quantdaddy Apr 17 '18 at 06:16