Home > Software design >  JWT (Token based authentication) vs Session / Cookies - Best Usage
JWT (Token based authentication) vs Session / Cookies - Best Usage

Time:09-17

I've been reading up on this topic a lot but could not find a good answer that I was looking for.

So my understanding of the pros and cons of JWT vs Session is

JWT pro

  • more scalable since no DB look up on server side. (assuming stateless JWT)

con

  • storage of token on client side needs to be well thought out. (cookie w/ httpOnly is preferable over local storage but cookie has 4kb size limit)
  • not immediately revocable
  • permissions can go stale until the next refresh

Session pro

  • arguably more secure since you are only passing around session id (opaque ref), easier to protect against CSRF than XSS, etc.
  • changes on user are reflected immediately.

con

  • less scalable than token

So given my understanding,

  1. which approach does website that supports huge number of users (amazon, uber) use? Is using session w/ distributed cache good enough?

  2. what is the real life use case where it makes more sense to use JWT (token based) over session based?

Thank you!

CodePudding user response:

JWTs were never designed for handling sessions. They are a way of exchanging integrity-protected messages between services. Have a look at this article: http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/ which explains why using JWTs for handling sessions is not a good idea.

You can also read about the BFF pattern: https://curity.io/resources/learn/the-bff-pattern/ where you use a lightweight backend component for handling tokens, and still deal only with sessions in the frontend. Because it's a light component it's easy to scale it - e.g. it can be a lambda function.

So in my opinion, there are no real good use cases where you genuinely prefer JWT-based session over cookie-based session, but (as any strong opinion), this may trigger a discussion ;)

  • Related