DEV Community

loading...

Discussion on: How to securely store JWT tokens.

gkoniaris profile image
George Koniaris Author • 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
quochuytlbk profile image
Huy Ta Quoc • 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
quochuytlbk profile image
Huy Ta Quoc

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.