Back to Security Academy
API SECURITYINTERMEDIATE6 min readCWE-942ZX-CORS-001

Fixing Permissive Wildcard CORS with Authenticated Credentials

Why Access-Control-Allow-Origin: * combined with credentials enables complete session hijacking, and how to configure strict origin whitelists.

Why AI coding tools introduce this vulnerability

AI tools frequently encounter cross-origin fetch errors during local dev and resolve them by adding res.setHeader("Access-Control-Allow-Origin", "*") or returning the incoming Origin header verbatim, completely defeating browser Same-Origin Policy protections.

Technical Vulnerability Analysis

A permissive Cross-Origin Resource Sharing (CORS) policy allows unauthorized third-party websites to issue authenticated cross-origin requests using a logged-in user's browser cookies. An attacker hosting malicious JavaScript on evil.com can extract sensitive user account data and execute actions without consent.

VULNERABLE IMPLEMENTATION (DO NOT USE)
// Express / Node.js AI-generated middleware
app.use((req, res, next) => {
  // Reflects ANY origin that asks!
  res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  next();
});
Reflecting req.headers.origin directly allows malicious sites to read authenticated API responses.

Remediation Playbook & Code Fixes

SECURE HARDENED PATCH (src/middleware.ts)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const ALLOWED_ORIGINS = new Set([
  'https://zerivex.tech',
  'https://zerivex.tech',
]);

export function middleware(req: NextRequest) {
  const origin = req.headers.get('origin');
  const res = NextResponse.next();

  if (origin && ALLOWED_ORIGINS.has(origin)) {
    res.headers.set('Access-Control-Allow-Origin', origin);
    res.headers.set('Access-Control-Allow-Credentials', 'true');
    res.headers.set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
    res.headers.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  }

  return res;
}

Why this fix works: Enforce an immutable Set of allowed origins. Reject unknown origins without setting CORS headers.

Local CLI Verification Commands

Verify malicious origin is not reflected in CORS response headers.
curl -sI -H "Origin: https://evil-attacker.com" https://example.com/api/user | grep -i "Access-Control-Allow-Origin"
Expected result: (empty response - header must NOT reflect evil-attacker.com)

Pre-Deployment Self-Audit Checklist

Knowledge Check: Verify Your Understanding

What is the primary architectural cause of fixing permissive wildcard cors with authenticated credentials?

Test your website for ZX-CORS-001

Run our 14 deterministic engines to inspect your live deployment.

Launch scan for this flaw