HIGH cross site request forgerybearer tokens

Cross Site Request Forgery with Bearer Tokens

How Cross Site Request Forgery Manifests in Bearer Tokens

Cross Site Request Forgery (CSRF) in Bearer Token contexts exploits the stateless nature of token-based authentication. Unlike session-based authentication where browsers automatically include cookies, Bearer Tokens require explicit inclusion in HTTP headers. This creates a false sense of security—developers assume that because tokens aren't automatically sent by browsers, they're immune to CSRF.

However, CSRF attacks against Bearer Tokens manifest through several attack vectors:

  • Malicious Page Embedding: An attacker hosts a page that makes fetch requests to a target API using the victim's browser context. Modern browsers enforce CORS policies, but misconfigurations or overly permissive CORS headers can allow these requests.
  • Hidden Form Submissions: While Bearer Tokens aren't automatically included in form submissions, attackers can use JavaScript to read tokens from localStorage or cookies and programmatically submit forms.
  • Clickjacking with Token Exposure: If an application's UI allows token extraction through DOM manipulation, clickjacking attacks can trigger API calls using those tokens.

The fundamental issue is that once a Bearer Token is stored in the browser (localStorage, sessionStorage, or cookies), any JavaScript running in that origin can access and use it. This breaks the same-origin policy's protective barrier for authenticated actions.

// Vulnerable pattern - token stored in localStorage
localStorage.setItem('authToken', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');

// Malicious page can read and use this token
const token = localStorage.getItem('authToken');
fetch('https://api.example.com/transfer', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ amount: 1000, to: 'attacker-account' })
});

Even with same-site cookies, if the token is accessible to JavaScript, CSRF remains possible. The attack becomes particularly dangerous when combined with XSS vulnerabilities, where an attacker can both read tokens and execute arbitrary requests.

Bearer Tokens-Specific Detection

Detecting CSRF vulnerabilities in Bearer Token implementations requires examining both the authentication mechanism and the application's security controls. Key detection methods include:

  • SameSite Cookie Configuration: Check if tokens stored in cookies use SameSite attributes. Missing or lax SameSite settings allow cross-site requests.
  • Referer Header Validation: Verify if the application validates the Referer header to ensure requests originate from trusted origins.
  • Double Submit Cookie Pattern: Look for implementations where a random token is stored in both a cookie and a hidden form field, then validated on the server.
  • CORS Policy Analysis: Examine Access-Control-Allow-Origin headers for overly permissive settings that allow cross-origin requests from any domain.
  • Token Storage Analysis: Identify where tokens are stored (localStorage, sessionStorage, cookies) and whether they're accessible to JavaScript.

Automated scanning with middleBrick specifically tests for these Bearer Token CSRF patterns by:

  • Attempting cross-origin requests with captured tokens to verify if the server accepts them
  • Checking for missing anti-CSRF tokens in state-changing operations
  • Analyzing CORS configurations for security weaknesses
  • Verifying SameSite cookie attributes on authentication tokens
  • Testing for clickjacking vulnerabilities that could expose token usage

The scanner examines the complete authentication flow, from token issuance through storage and usage, identifying specific weaknesses in how Bearer Tokens are protected against CSRF attacks.

Bearer Tokens-Specific Remediation

Securing Bearer Token implementations against CSRF requires multiple defensive layers. The most effective approach combines token storage strategies with server-side validation:

1. Secure Token Storage

Store tokens in HTTP-only, Secure, SameSite cookies rather than localStorage:

// Server sets token in HTTP-only cookie
res.cookie('authToken', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  maxAge: 3600
});

This prevents JavaScript access while maintaining automatic inclusion in requests.

2. Anti-CSRF Token Implementation

Implement double-submit cookie pattern or synchronizer tokens:

// Generate CSRF token on server
sessionStorage.setItem('csrfToken', crypto.randomUUID());

// Include in API requests
fetch('/api/protected', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'X-CSRF-Token': sessionStorage.getItem('csrfToken')
  }
});

3. Origin Validation

Validate request origins on the server:

app.use((req, res, next) => {
  const allowedOrigins = ['https://yourapp.com'];
  const origin = req.get('origin') || req.get('referer');
  
  if (allowedOrigins.includes(origin)) {
    return next();
  }
  
  res.status(403).json({ error: 'Invalid origin' });
});

4. CORS Configuration

Implement strict CORS policies:

app.use(cors({
  origin: 'https://yourapp.com',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Authorization', 'Content-Type', 'X-CSRF-Token']
}));

5. Content Security Policy

Add CSP headers to prevent unauthorized framing:

app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', 
    "frame-ancestors 'none'; default-src 'self'");
  next();
});

These combined measures create defense-in-depth protection. The HTTP-only cookie prevents JavaScript access, SameSite prevents cross-site inclusion, anti-CSRF tokens validate request legitimacy, and CSP headers prevent clickjacking attacks.

Frequently Asked Questions

Can't I just use SameSite cookies to prevent CSRF with Bearer Tokens?
SameSite cookies provide important protection but aren't sufficient alone. While SameSite=Strict prevents cross-site cookie inclusion, if your token is stored in localStorage or sessionStorage (common with SPA frameworks), SameSite doesn't help. Additionally, SameSite doesn't protect against same-site attacks or attacks that combine XSS with CSRF. You need multiple layers: secure storage, anti-CSRF tokens, origin validation, and proper CORS configuration.
How does middleBrick detect CSRF vulnerabilities in Bearer Token implementations?
middleBrick performs active testing by attempting cross-origin requests with captured tokens, checking for missing anti-CSRF protections on state-changing operations, analyzing CORS configurations for overly permissive settings, and verifying SameSite cookie attributes. The scanner also tests for clickjacking vulnerabilities and examines whether tokens are stored in accessible locations like localStorage. It provides specific findings about which CSRF protections are missing and their severity impact.