'JWT (Token based authentication) vs Session / Cookies - Best Usage

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!



Solution 1:[1]

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 ;)

Solution 2:[2]

JWT was born to provide secured access to APIs from mobile apps. Software developers started using them for web browser based clients as well but they are not suited due to security concerns. You will find many articles on this topic. For web application, it is best to store token at server side, link it with a new session, return the session after login to the web browser and store it in the session cookie.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ArSeN
Solution 2 Nitin Gaur