Where to Store Tokens
Not sure where to store tokens? This guide outlines how to securely store tokens used in token-based authentication.
Don't store tokens in local storage
Browser local storage (or session storage) is not secure. Any data stored there may be vulnerable to cross-site scripting. If an attacker steals a token, they can gain access to and make requests to your API. Treat tokens like credit card numbers or passwords: don’t store them in local storage.
If a backend is present
If your application has a backend server at all, then tokens should be handled server-side using the Authorization Code flow, Authorization Code flow with Proof Key for Code Exchange, or hybrid flow.
Single page applications
If you have a single page application (SPA) with no corresponding backend server, your SPA should request new tokens on page load and store them in memory without any persistence. To make API calls, your SPA would then use the in-memory copy of the token.
There are different options to control the lifetime of a cookie:
- Cookies can be destroyed after the browser is closed (session cookies).
- Implement a server side check (typically done for you by the web framework in use), and you could implement expiration or sliding window expiration.
- Cookies can be persistent (not destroyed after the browser is closed) with an expiration.
httpOnlyflag is set.
- You can set the
secure=trueflag so cookies can only be set over an encrypted connection.
- The max size of a cookie is only 4kb so that may be problematic if you have many claims attached to the token.
- Cookies can be vulnerable to cross-site request forgery (CSRF or XSRF) attacks. Using a web app framework’s CSRF protection makes cookies a secure option for storing a JWT. CSRF can also be partially prevented by checking the HTTP
Originheader. You can also set the
SameSite=strictcookie flag to prevent CSRF attacks.
- Can be difficult to implement if the application requires cross-domain access. Cookies have additional properties (Domain/Path) that can be modified to allow you to specify where the cookie is allowed to be sent.