Skip to content

re: How I Fixed JWT Security Flaws in 3 Steps VIEW POST


Hi, I think you built your localstorage critique on a wrong claim:

"Problem is: any JavaScript code in your frontend is able to access the JWT. And do whatever it wants."

The localstorage is isolated from other domains and only accessbile to scripts from the same domain. Those can manipulate the localstorage, as they can manipulate cookies from the same domain.

Cookies on the other hand can be used for CSRF attacks if CORS headers are not set correctly (see: ). They do have advantages though - you can set expiration/max-age times and they are sent also with links where you possibly cannot set Authorization headers like with file downloads.


Hi Johannes, those are very important concerns! I'm glad you raised them in this discussion!

You are absolutely right that other domains wouldn't be able to access your localStorage implementation. Nonetheless, this would be possible in case of an XSS attack to your site. This was the scenario I pointed out in the article:

"Imagine what can happen if someone manages to inject malicious code in your frontend... and get all your users' JWTs?"

CSRF is indeed a real threat to cookies. That's why I suggested setting them with the sameSite property:

"Make sure you flag it as Secure and httpOnly cookie. And SameSite cookie".

This protects your JWT against some CSRF attack vectors, but not your entire implementation. There are additional measures you should take, such as:

  • Implement a CSRF token
  • Avoid using the GET method for state-changing requests

Keeping JWT token in localStorage is fine. The only concern is XSS which should be avoided at all cost.
Once your site is vulnerable to XSS you got more bigger problem rather than just stealing JWT token.
So store the JWT token in localStorage and make sure your website is battle tested against XSS.

It can be "ok" and acceptable in some cases, but definitely not the best practice from a security standpoint.

A good analogy here would be our house. We need to secure doors and windows against unauthorized access. If a malicious actor gets in, we've got big problems, yes. But that doesn't mean we shouldn't hide our valuables. We may still store jewelry, money and other values in a safe. That practice can mitigate the losses in case someone breaks in the house.

code of conduct - report abuse