DEV Community

Discussion on: How to securely store JWT tokens.

Collapse
 
gkoniaris profile image
George Koniaris • Edited

Hello there,

Thanks for commenting. Cookies are XSS vulnerable in the case that we don’t set an HttpOnly flag in the server when creating the cookie. When the cookie is set with an HttpOnly flag it can’t be accessed by javascript in any way (at least in modern browsers, I don’t know what happens with ie 7 or 8 :p)

Collapse
 
inkeliz_35 profile image
Lucas Rodrigues • Edited

I think @quochuytlbk does not suppose that you want to steal the session, but use the session already active on the page. Let's assume that your website is vulnerable by XSS, then I can inject something like: fetch('api/account', {method: 'DELETE'}). I still don't know your session/cookie, but I manage to use them to delete your account. The fetch call was performed inside your website, it's not CSRF.

Thread Thread
 
gkoniaris profile image
George Koniaris • Edited

Nothing is 100% secure, but that would require that the attacker finds a way to inject code to specifically target my own web application. What you say is 100% valid, my approach is vulnerable to this kind of attack. But it would also be vulnerable if someone was using local storage. I don't know if there is any way that you can prevent this type of attack.

Thread Thread
 
itswillt profile image
Will T. • Edited

Lucas delivered what I failed to. So yes, that's the point. When an XSS vulnerability is exploited, nothing can save our users. The best bet is to prevent XSS from happening in the first place, or everything is vulnerable.
That being said, why would I go through all the trouble of trying to protect cookies from both CSRF and XSS, just to introduce a little bit of inconvenience to the attacker? At least with localStorage, I don't have to care about protecting against CSRF.
So in my opinion, using XSS as an exclusive drawback of localStorage can be misleading. When I first started to dig into the "localStorage vs Cookies" battle, I unknowingly thought it was "Protecting against XSS vs Protecting against CSRF". That is of course not true. It is "Protecting against XSS vs Protecting against CSRF and XSS".
I think one of the valid use cases of cookies over localStorage (or sessionStorage, IndexedDB, etc.) is SSR (where there is no localStorage).
Edit: Another valid use case of cookies is when you have subdomains because I've heard that localStorage doesn't work across subdomains.

Thread Thread
 
itswillt profile image
Will T.

So I have come to my own conclusion that it all depends on your use cases and how you use the methods. There is no "localStorage is totally better than cookies" or vice versa.