JWT in localStorage vs httpOnly cookie — which is safer?
posée 5 months ago569 vuesen
For my SPA's authentication, tutorials disagree: some store the JWT in localStorage, others in a cookie. What's the actual security difference?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
2 réponses
- localStorage: any JavaScript on your page can read it, so a single XSS bug (or a compromised npm dependency) lets an attacker steal the token and use it from anywhere until it expires. - httpOnly cookie: JavaScript can't read it. XSS can still make requests *from the victim's browser*, but it can't exfiltrate a long-lived credential. You must handle CSRF, which is largely addressed by SameSite=Lax (or Strict) plus checking Origin on state-changing requests.
Recommended for a browser app served from your own domain:
Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=...
Notes: - For a first-party web app, a plain server-side session cookie is often simpler than JWT and easier to revoke. - JWTs are handy for service-to-service calls and mobile clients (stored in secure storage). - Whatever you choose: short expiry, server-side revocation for "log out everywhere", and a strict Content Security Policy to reduce XSS risk in the first place.
Connectez-vous pour dire si ça a marché.
One nuance: if your API is on a different *site* than your frontend (not just a different subdomain), SameSite cookies get more complicated and third-party cookie restrictions apply. Serving the API under the same site (api.example.com for app.example.com) keeps cookies simple.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.