+91 98726 60544 hello@mitstech.co Mon–Sat · 09:00–18:30 IST

Sessions or tokens: choosing how to authenticate

Security By Mits Engineering Team 2 min read
Sessions or tokens: choosing how to authenticate

Somewhere in the last decade, JSON Web Tokens became the reflexive answer for authentication in new applications, including a great many that would have been better served by an ordinary session cookie. The reasoning offered is usually that tokens are stateless and therefore scale. The reasoning is true and the conclusion often does not follow, because statelessness is precisely what makes the hard problem hard.

A session works like this: the server creates a record, gives the browser an opaque identifier in a cookie, and looks that record up on each request. The properties that matter are that you can revoke it instantly by deleting the record, you can change a user's permissions and have it take effect on the next request, and you can list every active session for a user. The cost is a lookup per request, which against Redis is well under a millisecond.

A token works differently: the server signs a payload containing the user's identity and claims, and hands it over. Any server can verify the signature without a lookup, which is genuinely valuable when many independent services need to authenticate the same caller. The cost is that the token is valid until it expires, and there is no way to un-issue it. If you revoke access, the token keeps working. If you demote an administrator, they stay an administrator until expiry.

The usual response - a short expiry with refresh tokens - reintroduces server state to store and revoke the refresh tokens, which is the thing statelessness was supposed to avoid. That is a reasonable design, but be clear that you have arrived at sessions with extra steps and a more complex failure surface. If your application is a single API serving a browser, a session cookie is simpler, safer by default, and revocable.

Where tokens genuinely earn their place: many services verifying independently, third-party clients where you cannot rely on cookies, mobile applications, and machine-to-machine authentication with short-lived credentials. Those are real and common enough that tokens are not a mistake - they are a specific tool that got adopted as a default.

Whichever you choose, the storage decision in the browser is where most vulnerabilities enter. Cookies with HttpOnly, Secure and SameSite set are not readable by JavaScript, so a cross-site scripting flaw cannot steal them. Tokens in localStorage are readable by any script on the page, including anything a supply-chain attack put there. If you use tokens in a browser, put them in an HttpOnly cookie rather than localStorage, and add CSRF protection - and note that at this point you are again running something very like a session.

Need help with this? Explore our Cybersecurity & Compliance services. Learn more Back to all news

Keep reading

More on Security