mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.96k stars 213 forks source link

Example queries DB for each request #112

Closed mathieuprog closed 7 years ago

mathieuprog commented 7 years ago

As I understand it, the user is authenticated once with e.g. email/password and a token is generated. Then this library come to hand and allows me to validate the token received on each request requiring authentication.

One advantage of JWT tokens, is that the DB could potentially be queried only once (during first authentication/generation of token). However, in this default example, the DB will be queried for each request (requiring authentication) ; the example not only validates the token with the secret, but also checks if the id exists in the database and fetches the user ; is there any reason for that?

Shouldn't I just return the user id instead of fetching the user every time : return done(null, {id: jwt_payload.sub});

mikenicholson commented 7 years ago

I see where you're coming from - JWT's can be used as a means to provide stateless auth for an application which can reduce DB queries, etc. This all depends on how you implement the authentication scheme. This strategy does not provide a full authentication scheme on its own and is intended to be used as part of a larger auth scheme implemented by the developer.

Per RFC 7519:

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties.

In the case of the example code - it is a simplified snipped of an application that relied on a JWT sent from an Android application to provide authentication for users in our database. We validated the JWT against keys that Google made available via a public URL. Once we validated the JWT provided by the app we switched the client over to our own internal authentication scheme. This is a totally valid use of JWT's that required a DB query each time a JWT was provided to the endpoint.

The example is only intended to show how to construct and use the strategy. Its not intended to show best practices for implementing auth schemes. Since this module is intentionally small and intended to be used as only part of an authentication scheme it is probably beyond the scope of the README to presume any best practices or how the passport-jwt module should be used.