I am developing a project using Django REST API
(backend) and React JS
(front end). I am using Json Web token
for authentication. But I am confused at the point that whether should I store Json Web token
in local storage
or in the cookies
? Which one is more safe and why? How big companies handle this kind of security between API
and client side
?
For cookies, the maximum size is 4096 bytes, whereas for local storage it's 5MB. For that reason, cookies should not be used to store large pieces of data. For example, if you want to store the user's details in the browser then it's best to store them in the local storage.
Although cookies still have some vulnerabilities, it's preferable compared to localStorage whenever possible. Why? Both localStorage and cookies are vulnerable to XSS attacks, but it's harder for the attacker to do the attack when you're using httpOnly cookies.
No. localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want. That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.
Unlike Cookies where all Cookies (for that domain) are sent on each request, Local and Session Storage data aren't sent on each HTTP request. They just sit in your browser until someone requests it. Each browser has a different specifications on how much data can be stored inside Local and Session Storage.
The fundamental question is more secure against what?
The primary threat is cross-site scripting (xss). With regard to that, a cookie is definitely more secure, if and only if it is set as httpOnly.
However, if the auth info is in a cookie, cross-site request forgery (csrf) becomes an issue, and you have to implement csrf protection. Not the end of the world, but you need to care about it. If you store the auth token in localstorage and send it as a header, csrf is not an issue.
Also cookies with an expiry (persistent cookies) often get saved to plaintext files on the client, which may or may not be a valid threat in your threat model.
So in short, it depends. Overall, storing the token in an httpOnly, secure cookie is usually considered the most secure, but it has implications as described above. Storing the token in localstorage is acceptable too in most cases. Even more so because if you need to send the token to multiple backends (on different origins), you can't have it in a cookie, because that would only be sent to its own origin.
As always, the devil is in the (implementation) details.
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