DEV Community

Discussion on: Code smart, not hard

Collapse
andreasvirkus profile image
ajv

I'm struggling with the security aspect of keeping a JWT in localStorage. that's potentially the same as keeping the whole user session in a non-http cookie, for any js script to read.

I see most apps keep their JWT there, yet it makes no sense 🤭 (At the same time I do see the benefits and sexiness of a static SPA)

Collapse
solkimicreb profile image
Miklos Bertalan Author

This is a good point and it keeps coming back. There are some heated discussions about this and most articles are pretty one sided with a few slight half-truths against the other side.

I suggest you to read this article against local storage first.

I can't find a similarly good article for the pro-localstorage side but here are a few points to consider:

  • While LocalStorage is vulnerable against XSS, cookies are vulnerable aganst CSRF. Both are equally bad security issues and both can be mitigated (to some extent at least).

  • Server set httpOnly cookies are good for simple one server -> one client apps. When you need to open up your API you should not keep the session in cookies anymore. In these cases you should issues tokens to the clients and let them store them however they want to (DB on the server side or localStorage on client side). This is what oauth does as an example.

I am personally okay with both approaches and I try to secure things either way but I am not a security expert. It would be nice to hear the opinion of someone more experienced.

Collapse
andreasvirkus profile image
ajv

Keeping a JWT in localStorage doesn't just open you up to XSS, it also opens you up to session hijacking (a much more severe vulnerability imo). If someone/-thing grabs that token, then it has free access to your API for X amount of time. And since detecting that a 3rd party's or extension's script is reading something from your localStorage is impossible, then they can simply wait for the user to renew their session and attack again.