Is storing JWTs in localStorage still considered unsafe for modern web applications? #5155
-
🏷️ Discussion TypeQuestion BodyI'm working on a small web application that uses JWT authentication. Most tutorials I've found store the access token in My confusion is that if an attacker can execute JavaScript through an XSS vulnerability, the application already has bigger problems. On the other hand, many modern applications still seem to use localStorage for tokens. What are the practical security risks of storing JWTs in localStorage today, and under what circumstances would HttpOnly cookies be the better choice? I'd be interested in hearing how others handle authentication tokens in production applications. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I've used both approaches and the biggest issue with localStorage is token theft through XSS. If an attacker can run JavaScript in your application, they can usually read anything stored in localStorage and send it elsewhere. HttpOnly cookies help because the browser sends them automatically, but JavaScript can't read them directly. That doesn't magically solve all security problems though. If you're using cookies, you still need to think about CSRF protection. For internal tools and small projects I've seen localStorage used quite often because it's simple. For applications handling sensitive user data, I'd generally prefer HttpOnly cookies with SameSite enabled and short-lived access tokens. The choice really depends on your threat model, but if security is a priority, HttpOnly cookies are usually the safer default. |
Beta Was this translation helpful? Give feedback.
I've used both approaches and the biggest issue with localStorage is token theft through XSS.
If an attacker can run JavaScript in your application, they can usually read anything stored in localStorage and send it elsewhere.
HttpOnly cookies help because the browser sends them automatically, but JavaScript can't read them directly.
That doesn't magically solve all security problems though. If you're using cookies, you still need to think about CSRF protection.
For internal tools and small projects I've seen localStorage used quite often because it's simple.
For applications handling sensitive user data, I'd generally prefer HttpOnly cookies with SameSite enabled and short-lived access to…