Usage of Cookies/LocalStorage/SessionStorage for Sensitive Authentication Tokens Such as Session IDs/JWT
Publish date: Apr 28, 2025
The authentication tokens such as Session IDs, OAuth access token, refresh token etc usually need to be stored on the browser side to avoid unnecessary logins for every request. There are several options for this, each with its pros and cons which are described below.
Cookies
Cookies are ideal for storing tokens. They provide both protection from token stealing via XSS (HTTPOnly flag) as well as built in expiry mechanism.
However, they are harder to use if setting cookies is not already supported by server side, if the framework requires manipulation/usage in javascript layer, or they need to be sent to another domain.
If feasible, cookies should be used for storing any token. Care should be taken to make sure that the tokens are preferably short lived, that cookies are cleared properly on logout/timeout, and that appropriate flags (Secure, HTTPOnly) are set.
Session Storage
Session Storage is useful for single page apps. When cookies are not feasible for token storage (e.g. need to use token in javascript layer or in cross domain requests), Session Storage is an acceptable choice. This storage is automatically cleared once a tab is closed, making it relatively safer for usage compared to Local Storage. This would still be exposed to token stealing via XSS attacks.
When used, it is strongly recommended that it is used only for short lived tokens and not for long lived tokens. Any long lived tokens could be stored on server side if a session is maintained, or encryption could be performed on the tokens to obfuscate them. To avoid multiple logins across tabs, the tabs can potentially use secure cross window messaging to share tokens with each other.
Local Storage
The Local Storage data persists across browser sessions unlike session storage, and can be accessed by JS as well as it doesn’t expire unlike HTTPOnly cookies. That’s the reason why it is only recommended as a place for storing user preferences and other such information which is not critical to security but helps maintain the application view the way user wants for a long time.