highCWE-922A07:2021

Authentication Tokens in localStorage

Storing JWT tokens, session tokens, or API keys in localStorage makes them accessible to any JavaScript running on the page, including XSS payloads.

How It Works

localStorage is accessible to any JavaScript running on the same origin. If an attacker achieves even a minor XSS vulnerability, they can extract all tokens with a single line: document.cookie is protected by HttpOnly, but localStorage has no such protection. Stolen tokens allow session hijacking, account takeover, and API abuse. Unlike cookies, localStorage values are never automatically sent with requests, so developers must manually attach them — often in ways that expose them to CSRF or XSS. Tokens in localStorage also persist after the browser is closed, extending the attack window.

Vulnerable Code
// After login
const { token } = await response.json();
localStorage.setItem('auth_token', token);

// On every request
fetch('/api/data', {
  headers: { Authorization: `Bearer ${localStorage.getItem('auth_token')}` }
});
Secure Code
// Server sets HttpOnly cookie after login
// In API route:
res.setHeader('Set-Cookie', serialize('session', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',
  maxAge: 60 * 60 * 24 * 7
}));

// Client requests automatically include the cookie
fetch('/api/data', { credentials: 'include' });

Real-World Example

In 2022, an XSS vulnerability in a popular React dashboard allowed attackers to steal JWTs from localStorage of admin users. The tokens had long expiration times (30 days), giving attackers persistent access to admin panels and customer data.

How to Prevent It

  • Store tokens in HttpOnly, Secure cookies instead of localStorage
  • Set SameSite=Lax or Strict on authentication cookies
  • Use short token expiration times with refresh token rotation
  • Implement Content Security Policy to reduce XSS attack surface

Affected Technologies

ReactNext.jsNode.js

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities