.NET › Authentication & Authorization (Identity, JWT, OAuth)
What are the security risks of storing JWTs in browser localStorage versus HttpOnly cookies?
IntermediateAnswer
Tokens in localStorage are accessible to any JavaScript running on the page, making them vulnerable to theft via XSS (cross-site scripting) attacks -- a single injected malicious script can read and exfiltrate the token. HttpOnly cookies are inaccessible to JavaScript entirely, protecting against XSS token theft, but introduce CSRF (cross-site request forgery) risk instead, requiring anti-forgery tokens or SameSite cookie attributes as mitigation.
// Vulnerable to XSS if an attacker injects a script:
localStorage.setItem('token', jwt); // any XSS payload can steal this
// HttpOnly cookie: JavaScript cannot read it at all
Response.Cookies.Append("auth_token", jwt, new CookieOptions {
HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict
});Real-world example A security review flags a single-page application storing JWTs in localStorage as a critical risk given the app also loads several third-party analytics scripts, recommending a move to HttpOnly cookies with CSRF protection instead.