I'm familiar with Web Storage APIs and cookies but I can't figure what is the most secure way to store an authentication token. I'm wondering if this might break any third-party libraries.
I'd like to have an exhaustive list of available methods to do so, with the pros and cons of each and the best way above all, if any.
To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.
There are two critical steps in using JWT securely in a web application: 1) send them over an encrypted channel, and 2) verify the signature immediately upon receiving it. The asymmetric nature of public key cryptography makes JWT signature verification possible.
If in any case more than one JWT can be generated for a user for a single purpose like an email verification token, or reset password token in those cases we must save the tokens/latest token in DB to match with the most recent one.
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.
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.
Click here for an example using sessionStorage
Both localStorage
and 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.
You can also use cookies to store the JWT. The exact way to set a cookie depends on the client side language you are using.
There are different options to control the lifetime of a cookie:
httpOnly
flag is set.Referer
and Origin
header.Original article: https://auth0.com/docs/security/store-tokens#how-to-implement
Checkout this for motivation
The most secure option is in-memory. Checkout this for a deep dive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With