DEV Community

loading...

Discussion on: localStorage vs cookies: the "tabs vs spaces" sterile debate of web development 🙄

Collapse
oguimbal profile image
Olivier Guimbal Author

That's the thing. My point is that this is a dogma that I feel is not true when you deal with smaller projects, or with junior developers. You can write broken auth mechanisms even more easily when using cookies compared to storing a token in localStorage.

See my edit (on top of the article for the "server to know" part).

Collapse
darkwiiplayer profile image
DarkWiiPlayer

You can write broken auth mechanisms using anything if you don't know what you're doing. It's the reason why we don't trust beginners to write security-related code until they have developed a good understanding of the implications.

Ultimately, if an attacker has gotten to the point of running arbitrary code in your system, be it clientside or serverside, you're screwed either way. This is an all or nothing situation. You can't be somewhat dead or, as my math teacher used to put it, there is no half pregnant (not even the weirdest one of her pet phrases).

So yes, if the server needs to know (anew with every request), a cookie is the right place to put the data. If the server generally doesn't need to know, then local storage.

Thread Thread
oguimbal profile image
Olivier Guimbal Author • Edited

Totally agree on the "all or nothing situation". But if you assume that your client is somewhat safe, then its safer to never use cookies (you're protecting yourself against XSRF), and prefer passing an 'Authorization' header in your requests filled with a token you'll keep in localStorage.

You've made me realize that this might be another confusion: I'm speaking about SPAs ... for which the only required auth is via Ajax calls (meaning you have control over headers). I'll edit more.

Thread Thread
darkwiiplayer profile image
DarkWiiPlayer

For SPAs it's a bit easier to use localstorage, but I still think cookies are the place to transmit tokens: their whole point is to transmit certain data with every request, so I don't see much of a point in re-inventing the wheel. For XSRF there's specific mechanisms to mitigate it.

What's more, with cookies, the browser keeps track of what goes to which domain, whereas if you manually insert a header into every fetch request, you might by mistake end up sending the token to the wrong domain, if an attacker finds a way to inject an off-domain URL into your application.

Thread Thread
oguimbal profile image
Olivier Guimbal Author

You can mitigate this very easily. That's what CSPs are for.

Actually, it's much more easy and reliable than mitigating XSRF, given that you just have to do it once, and it does not require any code... (you can just put the right CSP in your CDN config)