Search code examples
reactjssecuritydjango-rest-frameworkjwtsoftware-design

Which one is more safe local storage or cookies?


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?


Solution

  • 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.