DEV Community

Discussion on: What are the good practices to Node.js web app authentication and authorization?

Collapse
 
dpashutskii profile image
Dmitrii Pashutskii • Edited

I've also used Reddit to discuss this topic and I just copy one answer which I found really helpful and maybe it'll be useful for someone else:

The way I usually do it looks something like this:

  1. Client sends a login request with a username/password
  2. Server validates the credentials and creates a JWT with a payload that includes the user's id.
  3. Server sets the JWT as an httponly cookie on the response
  4. Client sends request for protected resource
  5. Server checks if the auth token cookie is set and is a valid JWT.
  6. If the JWT is valid, the server continues the request. Otherwise, it responds with a 401 status.
  7. Usually the JWT middleware will provide the parsed JWT payload (the user's id) to downstream middleware/handlers.

There's a bunch of details that could change. For example, you could send the JWT to the client and store it in memory then attach it to every request using the Authorization header. The payload can also change. If you want to more session data on the server, you might have a session table and just store { sessionId: ... } in the JWT. There are even some use-cases where you store additional data in the JWT (you can really put any data in there), but the data could become stale if it changes after you issue the token to the client. I'd shoot for putting as little data in the token as possible. Ideally data that won't change.

You likely won't need to store the JWT in your database. The only reason I can see for storing them is to allow you to invalidate them (though if you're just storing a session id in the JWT, you could just delete the session).

Kudos to this gentleman: reddit.com/r/node/comments/dx2g93/...

Collapse
 
souksyp profile image
Souk Syp.

Use Redis for session storage.