Where to Store Tokens
This document explains how to securely store tokens used in token-based authentication. The following assumes a basic knowledge of JSON Web Tokens (JWTs). To learn more about JWTs see:
Where to Store Your JWTs
With token-based authentication, you are given the choice of where to store the JWT. We strongly recommend that you store your tokens in local storage/session storage or a cookie.
Web Storage (local storage/session storage)
Commonly, the JWT is placed in the browsers local storage and this works well for most use cases.
When logging in a user with a username and password, the response body contains the
access_token JWT. Then you need to handle this response in the client side code. This token can then be stored in localStorage or sessionStorage.
sessionStorage both extend
Storage. The only difference between them is the persistance of the data:
localStorage - data persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
sessionStorage - Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
Web Storage Disadvantages
- Unlike cookies, local storage is sandboxed to a specific domain and its data cannot be accessed by any other domain including sub-domains.
- The developer must ensure that the JWT is always sent over HTTPS and never HTTP.
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.
- 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 cross-site request forgery (CSRF or XSRF) attacks. This type of attack occurs when a malicious web site causes a user’s web browser to perform an unwanted action on a trusted site where the user is currently authenticated. This is an exploit of how the browser handles cookies. Using a web app framework’s CSRF protection makes cookies a secure optionfor storing a JWT. CSRF can also be partially prevented by checking the HTTP
- 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.
How to implement
Many of our Quickstarts demonstrate how to store tokens, and the exact implementation will be different based on the technology being used. Please refer to the Quickstarts at the top of our Documentation Home Page, select the appropriate Quickstart based on your application type, and follow the code samples provided.