Search code examples
node.jsauthenticationjwtjwt-simple

does JWT containing userID need verification from the database?


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.


Solution

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