1

In the context of a web application... should sensitive tokens, such as those used for sessions, authentication and/or authorization, be stored in localStorage or an HTTPOnly cookie; or are they both acceptable approaches in different circumstances?

For the purposes of this question, assume that the token in question, whatever form it might take, could be leveraged to impersonate the user / hijack their session if it were disclosed to an adversary.

Background

My personal understanding / belief has always been that HTTPOnly cookies are the optimal security choice in these situations, due to the risks associated with cross-site scripting. OWASP's HTML5 cheat sheet recommends the same.

Pro HTTPOnly cookies:

  • A successful cross-site scripting attack cannot access the token.
  • Malicious browser extensions cannot access the token.
  • Exploiting the token is more difficult for the attacker, who has to make XMLHttpRequests through the victim's browser (when the token will be automatically attached to the request).

Pro localStorage / sessionStorage:

  • Cross-site request forgery attacks are entirely prevented.

To me, both XSS and CSRF attacks are complex to protect against and would both benefit from multiple layers of security controls as a result. I.e. I see experienced development teams still produce applications with the occasional XSS and/or CSRF bug - protecting against these issues universally and at scale can be challenging.

localStorage appears to completely resolve CSRF, but leaves the token accessible to malicious JavaScript in the event of an XSS bug. HTTPonly cookies partially mitigate XSS but introduce CSRF as a new attack vector, which has to be protected against via its own controls. The impact of an XSS attack is potentially higher than CSRF.

itscooper
  • 2,230
  • 13
  • 15
  • It seems you have done your homework and have a correct view of cookies and localStorage. I am not sure there is a clear-cut answer to this question. – Sjoerd Dec 11 '18 at 08:10
  • I'd go for `HTTPOnly` Cookie. CSRF and XSS are both different and require separate mitigation technique for each. XSS always defeats CSRF, even protected ones. While CSRF doesn't have anything to do with XSS. It's also worth noting that we now have `SameSite` cookies which prevents CSRF altogether if done correctly. – 1lastBr3ath Dec 11 '18 at 13:52
  • localStorage lives on the hard drive, providing a physical interception vuln that such cookies don't – dandavis Dec 12 '18 at 17:42

1 Answers1

0

Your description is correct. The use of cookies has the preference here in terms of security.

However, the HttpOnly flag is not the only thing that is required for optimal security. Set the SameSite flag to strict for best CSRF protection. Set the Path attribute if the scope can be narrowed to a specific path within the domain. Set the Secure flag to ensure it is broadcast over HTTPS only. Lastly, consider using the __Host- prefix.

Wouter
  • 397
  • 1
  • 12