1 Secure ReactJS App
djmil edited this page 2023-08-27 16:58:44 +02:00

JWT vs Server-side Session

Sessions

With server-side sessions, you will either have to store the session identifier in a database, or else keep it in memory and make sure that the client always hits the same server. Both of these have drawbacks. In the case of the database (or other centralised storage), this becomes a bottleneck and a thing to maintain - essentially an extra query to be done with every request.

With an in-memory solution, you limit your horizontal scaling, and sessions will be affected by network issues (clients roaming between Wifi and mobile data, servers rebooting, etc).

JWT

Moving the session to the client means that you remove the dependency on a server-side session, but it imposes its own set of challenges.

  • Storing the token securely.
  • Transporting it securely.
  • JWT sessions can sometimes be hard to invalidate.
  • Trusting the client's claim.

These issues are shared by JWTs and other client-side session mechanisms alike.

JWT, in particular, addresses the last of these. It may help to understand what a JWT is:

It is a bit of information. For user sessions, you could include the username and the time when the token expires. But it could conceivably be anything, even the session ID or the user's entire profile (please don't do that though). It has got a secure signature that prevents malicious parties from generating fake tokens (you need access to the server's private key to sign them and you can verify that they were not modified after they were signed). You send them with every request, just like a cookie or Authorization Header would be sent. In fact, they are commonly sent in the HTTP Authorization header but using a cookie is fine too.

https://www.rdegges.com/2018/please-stop-using-local-storage/