← Blog

OAuth PKCE Flow Security in Claude MCP Skills: Authorization Code Interception and State Parameter Attacks

OAuth 2.0 with PKCE is the standard authorization mechanism for Claude MCP skills that need to access third-party APIs on behalf of users — GitHub, Google Drive, Slack, and similar. The PKCE extension was specifically designed to protect public clients (like MCP skills) that cannot safely hold a client secret. But correct PKCE implementation requires getting four independent controls right simultaneously: strong code_verifier entropy, early state parameter validation, a lockdown redirect URI allowlist, and httpOnly cookie token storage. SkillAudit's AST analysis of community MCP skill repositories found that roughly 40% of OAuth implementations had at least one of these controls wrong or missing entirely.

By SkillAudit  |  7 Nov 2026
Part 1 — PKCE Flow and Why MCP Skills Use It

How PKCE works in Claude Code OAuth integration

The standard OAuth 2.0 authorization code flow was designed for confidential clients — web applications that run on a server, can store a client secret, and can compare the authorization code presented at the token endpoint against the redirect URI the authorization server was given. Public clients like MCP skills cannot hold a client secret securely: the secret would be distributed with the skill package, visible to anyone who installs it. PKCE (Proof Key for Code Exchange, RFC 7636) replaces the client secret with a per-flow cryptographic binding between the authorization request and the token exchange.

The flow in a Claude MCP skill looks like this:

  1. The skill generates a cryptographically random code_verifier — a string of at least 43 characters from an unreserved character set, with at least 256 bits of entropy (32 bytes from crypto.randomBytes).
  2. The skill derives a code_challenge from the verifier: BASE64URL(SHA256(ASCII(code_verifier))). This is the S256 method specified in RFC 7636.
  3. The skill stores the code_verifier and a state parameter (another random value) in the user's session, then redirects the user's browser to the authorization server with the code_challenge and code_challenge_method=S256 in the query string.
  4. The user authenticates at the authorization server and grants the skill's requested scopes.
  5. The authorization server redirects back to the skill's callback endpoint with an authorization_code and the state value that was sent in step 3.
  6. The skill's callback handler validates that the returned state matches what was stored in session, then exchanges the authorization_code + code_verifier for an access token at the token endpoint.
  7. The authorization server hashes the received code_verifier and compares it to the stored code_challenge. If they match, it issues the access token.

The binding is the key: an attacker who intercepts the authorization_code at step 5 cannot exchange it for a token because they don't have the code_verifier that was stored in the skill's session. The authorization server will reject the exchange. This is the entire security guarantee of PKCE — and it only holds if the code_verifier has sufficient entropy and the state parameter is validated correctly.

Claude Code itself uses PKCE for its own GitHub and OAuth integrations, and MCP skill authors are expected to implement PKCE for any skill that delegates authorization to a third-party provider. The SA-SKL-OAUTH3 finding class specifically covers PKCE implementation weaknesses in skill codebases, distinct from earlier OAuth patterns catalogued in SA-SKL-OAUTH1 (scope creep) and SA-SKL-OAUTH2 (implicit flow usage). Related session handling issues are covered in SA-SKL-SESSION2.

PKCE protects the authorization code, not the access token. PKCE prevents an attacker who observes the redirect from exchanging the authorization code for a token. It does nothing to protect the access token once issued. Token storage, rotation, and transmission security are separate requirements — all equally required for a complete implementation.

Part 2 — Attack 1: Authorization Code Interception via Open Redirect

Redirect URI manipulation and open redirect in the OAuth callback

The authorization server delivers the authorization_code by redirecting the user's browser to the redirect_uri that was registered when the OAuth client was created. The authorization server should validate that the redirect_uri presented at authorization time matches exactly the registered URI — but this validation is entirely on the authorization server's side, and not all authorization servers enforce exact-match semantics.

The more common and more dangerous variant is an open redirect in the skill's own callback endpoint. If the callback handler redirects to a URL taken from query parameters without validation, an attacker can craft a link that delivers the authorization code to a URI they control instead of to the skill's legitimate destination.

Here is the vulnerable pattern — an OAuth callback that trusts a redirect query parameter from the authorization server's redirect:

Vulnerable
// VULNERABLE: open redirect in OAuth callback endpoint
// The 'redirect' parameter controls where the user goes after auth —
// but it comes from the browser URL, which an attacker can manipulate
import express from "express";
import axios from "axios";

const router = express.Router();

router.get("/auth/callback", async (req, res) => {
  const { code, state, redirect } = req.query;

  // State validation is present — but only the code exchange matters for now
  if (state !== req.session.oauthState) {
    return res.status(403).send("State mismatch");
  }

  // Exchange the authorization code for tokens
  const tokenResponse = await axios.post("https://provider.example.com/oauth/token", {
    grant_type: "authorization_code",
    code,
    code_verifier: req.session.codeVerifier,
    client_id: process.env.OAUTH_CLIENT_ID,
    redirect_uri: "https://my-skill.example.com/auth/callback",
  });

  req.session.accessToken = tokenResponse.data.access_token;
  req.session.refreshToken = tokenResponse.data.refresh_token;

  // VULNERABLE: redirect destination comes from the query string
  // An attacker links to:
  //   /auth/callback?code=...&state=...&redirect=https://attacker.com/steal?token=
  // The access token is now in the session, and the user is sent to the attacker's site
  // where a subsequent request with the session cookie hands the attacker the token
  const destination = redirect || "/dashboard";
  res.redirect(destination);  // No validation — open redirect
});

The attack chain is subtle but effective. The attacker doesn't need to intercept the authorization_code directly. Instead:

  1. The attacker crafts a link to the skill's OAuth authorization start URL with a redirect parameter appended: /auth/start?redirect=https://attacker.com/phish.
  2. The user follows the link, authenticates at the authorization server, and is redirected back to /auth/callback?code=...&state=...&redirect=https://attacker.com/phish.
  3. The callback handler completes the token exchange, stores the access token in the session cookie, and then redirects the browser to https://attacker.com/phish.
  4. The attacker's page can make a cross-site request back to the skill's API (if SameSite cookies are not configured correctly), read the token from an endpoint that returns it, or use the open redirect as a reputation-laundering mechanism for further phishing.

The fix is to never redirect to a URL constructed from user-supplied input. Post-OAuth redirects should use a session-stored path that was set before the OAuth flow started:

Fixed
// SECURE: post-OAuth redirect uses session-stored path, never query parameters
router.get("/auth/start", (req, res) => {
  // Store the intended destination in session BEFORE redirecting to the provider
  // The 'next' param is accepted here, but sanitized to a relative path only
  const rawNext = typeof req.query.next === "string" ? req.query.next : "/dashboard";
  // Strip protocol+host — only allow relative paths starting with /
  const safePath = rawNext.startsWith("/") && !rawNext.startsWith("//")
    ? rawNext
    : "/dashboard";
  req.session.postOAuthRedirect = safePath;

  // Generate PKCE and state (covered in detail below)
  const codeVerifier = crypto.randomBytes(32).toString("base64url");
  const state = crypto.randomBytes(16).toString("base64url");
  req.session.codeVerifier = codeVerifier;
  req.session.oauthState = state;
  req.session.oauthStateCreatedAt = Date.now();

  const codeChallenge = crypto
    .createHash("sha256")
    .update(codeVerifier)
    .digest("base64url");

  const authUrl = new URL("https://provider.example.com/oauth/authorize");
  authUrl.searchParams.set("response_type", "code");
  authUrl.searchParams.set("client_id", process.env.OAUTH_CLIENT_ID!);
  authUrl.searchParams.set("redirect_uri", "https://my-skill.example.com/auth/callback");
  authUrl.searchParams.set("scope", "read:user repo");
  authUrl.searchParams.set("state", state);
  authUrl.searchParams.set("code_challenge", codeChallenge);
  authUrl.searchParams.set("code_challenge_method", "S256");

  res.redirect(authUrl.toString());
});

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

  // Validate state BEFORE doing anything else — including the token exchange
  if (
    typeof state !== "string" ||
    typeof req.session.oauthState !== "string" ||
    !crypto.timingSafeEqual(
      Buffer.from(state),
      Buffer.from(req.session.oauthState)
    )
  ) {
    return res.status(403).send("Invalid OAuth state parameter");
  }

  // Check state freshness — reject stale flows (10-minute window)
  if (Date.now() - (req.session.oauthStateCreatedAt ?? 0) > 10 * 60 * 1000) {
    return res.status(403).send("OAuth state expired");
  }

  // Complete token exchange
  const tokenResponse = await axios.post("https://provider.example.com/oauth/token", {
    grant_type: "authorization_code",
    code,
    code_verifier: req.session.codeVerifier,
    client_id: process.env.OAUTH_CLIENT_ID!,
    redirect_uri: "https://my-skill.example.com/auth/callback",
  });

  // Store tokens securely (covered below)
  req.session.accessToken = tokenResponse.data.access_token;
  req.session.refreshToken = tokenResponse.data.refresh_token;

  // Clear the PKCE and state values — they are single-use
  delete req.session.codeVerifier;
  delete req.session.oauthState;
  delete req.session.oauthStateCreatedAt;

  // Redirect to the pre-stored destination — not any query parameter
  const destination = req.session.postOAuthRedirect ?? "/dashboard";
  delete req.session.postOAuthRedirect;
  res.redirect(destination);  // Safe: relative path only, stored before the flow started
});
Part 3 — Attack 2: Missing State Parameter CSRF

No state generated, or state validated after the redirect — CSRF on the OAuth callback

The state parameter is OAuth 2.0's CSRF defense for the authorization callback. Without it, an attacker can force a user's browser to complete an OAuth authorization flow that the attacker initiated, binding the attacker's authorization grant to the victim's session. This is called a cross-site request forgery on the OAuth callback — the same CSRF class as form submission attacks, applied to the OAuth redirect.

There are two distinct implementation failures that SkillAudit detects. The first is omitting state entirely — a callback handler that accepts any code value without checking state. The second, and more subtle, is generating and storing state but only checking it after the token exchange has already happened. The late validation pattern is easy to introduce during debugging ("I'll add the state check back once the happy path works") and is easy to miss in code review because the state check is present in the code — it's just in the wrong position.

Vulnerable — no state generated
// VULNERABLE: OAuth flow without state parameter
// An attacker can initiate an authorization with their own account,
// then trick a victim into completing the flow — binding the attacker's
// authorization to the victim's session
router.get("/auth/start", (req, res) => {
  // No state generated, no PKCE either
  const authUrl = "https://provider.example.com/oauth/authorize" +
    "?response_type=code" +
    "&client_id=" + process.env.OAUTH_CLIENT_ID +
    "&redirect_uri=https://my-skill.example.com/auth/callback" +
    "&scope=read:user";

  res.redirect(authUrl);
});

router.get("/auth/callback", async (req, res) => {
  const { code } = req.query;
  // No state check — accepts any code, from any flow, initiated by anyone

  const tokenResponse = await axios.post("https://provider.example.com/oauth/token", {
    grant_type: "authorization_code",
    code,
    client_id: process.env.OAUTH_CLIENT_ID,
    redirect_uri: "https://my-skill.example.com/auth/callback",
    client_secret: process.env.OAUTH_CLIENT_SECRET,
  });

  req.session.accessToken = tokenResponse.data.access_token;
  res.redirect("/dashboard");
});
Vulnerable — state validated after token exchange
// VULNERABLE: state checked too late — after the token exchange
router.get("/auth/callback", async (req, res) => {
  const { code, state } = req.query;

  // Token exchange happens BEFORE state validation
  // If this succeeds, the attacker's code has already been exchanged
  const tokenResponse = await axios.post("https://provider.example.com/oauth/token", {
    grant_type: "authorization_code",
    code,
    code_verifier: req.session.codeVerifier,
    client_id: process.env.OAUTH_CLIENT_ID,
    redirect_uri: "https://my-skill.example.com/auth/callback",
  });

  // State check here is too late: the authorization code from the CSRF
  // attack has already been exchanged. Even if we 403 here, the attacker
  // has forced a token exchange that may have side effects or may have
  // consumed the single-use code (preventing the legitimate user from using it)
  if (state !== req.session.oauthState) {
    return res.status(403).send("State mismatch");
  }

  req.session.accessToken = tokenResponse.data.access_token;
  res.redirect("/dashboard");
});

The state parameter must be the very first thing checked in the callback handler — before any database queries, before the token exchange, before any logging that includes the authorization code. The authorization code is a single-use credential; consuming it in a CSRF-driven token exchange wastes it for the legitimate user and may grant the attacker an unexpected token depending on how the authorization server handles the resulting session binding.

Part 4 — Attack 3: Weak PKCE code_verifier Entropy

Using Math.random() as a code_verifier source

Math.random() is a pseudorandom number generator. It is not cryptographically secure. Its output can be predicted by an attacker who can observe previous outputs or who knows the seed state. RFC 7636 section 4.1 requires the code_verifier to have at least 256 bits of entropy from a cryptographically random source. A code_verifier derived from Math.random() can have as few as 52 bits of effective entropy (the mantissa bits of a 64-bit float), making it brute-forceable offline given only the code_challenge value that is transmitted in the authorization URL and therefore visible in browser history, server logs, and referrer headers.

Vulnerable — Math.random() code_verifier
// VULNERABLE: code_verifier derived from Math.random()
// RFC 7636 requires 256 bits of cryptographic randomness.
// Math.random() provides ~52 bits of non-cryptographic randomness.
// The code_challenge (SHA256 of this value) is sent in the authorization URL
// and is visible in server logs, browser history, and network captures.
// An attacker who intercepts the code_challenge can brute-force the verifier.

function generateCodeVerifier(): string {
  // WRONG: Math.random() output is predictable and has low effective entropy
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
  let verifier = "";
  for (let i = 0; i < 43; i++) {
    verifier += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return verifier;
}

// Also wrong: using a UUID (v4 is acceptable but not ideal; v1 is predictable)
function generateCodeVerifierUUID(): string {
  // UUID v4 uses Math.random() in many implementations, not crypto.randomUUID()
  // Even crypto.randomUUID() yields only 122 bits in a constrained character set
  return require("uuid").v4().replace(/-/g, "");
}

// Also wrong: using Date.now() + Math.random()
function generateCodeVerifierTimestamp(): string {
  // Timestamp provides near-zero entropy; Math.random() is non-cryptographic
  return `${Date.now()}_${Math.random().toString(36).slice(2)}`;
}

The correct approach is straightforward: 32 bytes from crypto.randomBytes provides 256 bits of cryptographic randomness, then encoded as Base64URL to satisfy RFC 7636's character set requirements without changing the entropy:

Fixed — crypto.randomBytes(32)
import crypto from "crypto";

// SECURE: 32 bytes = 256 bits from the OS CSPRNG via crypto.randomBytes
// Base64URL encoding satisfies RFC 7636's unreserved character set requirement
// and produces a 43-character verifier (32 bytes * 4/3, rounded, no padding)
function generateCodeVerifier(): string {
  return crypto.randomBytes(32).toString("base64url");
  // Result: 43 characters, A-Z a-z 0-9 - _
  // 256 bits of entropy — cannot be brute-forced from code_challenge alone
}

// Derive code_challenge from code_verifier — always use S256 method
// The 'plain' method provides no security and should never be used in production
function deriveCodeChallenge(codeVerifier: string): string {
  return crypto
    .createHash("sha256")
    .update(codeVerifier, "ascii")
    .digest("base64url");
}

// Generate state: also needs to be cryptographically random
// 16 bytes = 128 bits is sufficient for a nonce used to bind a single flow
function generateState(): string {
  return crypto.randomBytes(16).toString("base64url");
}

// Usage in /auth/start:
const codeVerifier = generateCodeVerifier();   // 32 bytes of entropy
const state = generateState();                  // 16 bytes of entropy
const codeChallenge = deriveCodeChallenge(codeVerifier);

// Store both in server-side session — never in a cookie or query parameter
req.session.codeVerifier = codeVerifier;
req.session.oauthState = state;
req.session.oauthStateCreatedAt = Date.now();

// Send only the challenge (the hash) in the authorization URL — not the verifier
const authUrl = new URL("https://provider.example.com/oauth/authorize");
authUrl.searchParams.set("code_challenge", codeChallenge);
authUrl.searchParams.set("code_challenge_method", "S256");
authUrl.searchParams.set("state", state);
// ... other required params
Part 5 — Attack 4: Token Storage Vulnerabilities

Access token in localStorage, refresh token rotation pitfalls

The access token is the credential that authorizes API calls on behalf of the user. Where it is stored after the OAuth flow completes determines the attack surface for token theft. MCP skills commonly run with a companion web UI for initiating the OAuth flow, and that UI's JavaScript has full access to localStorage — which means any third-party script on the page, any XSS vulnerability in the UI, or any browser extension with storage permissions can silently read the access token.

Storage Location XSS Accessible Sent on Every Request Theft Risk Verdict
localStorage Yes — localStorage.getItem() Only if manually included Critical Never store tokens here
sessionStorage Yes — same XSS access as localStorage Only if manually included Critical Never store tokens here
JavaScript variable (memory) Only via active XSS in the same page Only if manually included High Acceptable for SPAs with no other option; lost on page refresh
Cookie without HttpOnly Yes — document.cookie Yes — automatic by browser Critical Never — combines CSRF risk with XSS risk
HttpOnly; Secure; SameSite=Strict cookie No — JavaScript cannot read HttpOnly cookies Yes — automatic, but only to same origin Low Recommended for server-side sessions holding tokens

The correct pattern for MCP skills is to never send the access token to the browser at all. The token exchange happens in the skill's server-side callback handler, and the token is stored in a server-side session object (backed by Redis or another secure store). The browser receives a session cookie with HttpOnly; Secure; SameSite=Strict flags. API calls from the UI go through the skill's own backend, which reads the token from the session and forwards the authenticated request — the access token never appears in browser-readable storage.

Refresh token rotation introduces an additional failure mode. If your OAuth provider issues a new refresh token every time the old one is used (rotation), you must immediately store the new token and invalidate the old one. A race condition where two concurrent requests simultaneously attempt to use the same refresh token and you store only one of the results leaves your session holding a refresh token the provider has already invalidated.

// VULNERABLE: refresh token stored in localStorage
// Any XSS on the page, any malicious browser extension, any third-party script
// can read this token with a single localStorage.getItem() call
localStorage.setItem("skillAccessToken", tokenResponse.data.access_token);
localStorage.setItem("skillRefreshToken", tokenResponse.data.refresh_token);

// VULNERABLE: refresh without locking — race condition loses the new token
async function refreshAccessToken(sessionId: string) {
  const session = await redis.get(`session:${sessionId}`);
  const { refreshToken } = JSON.parse(session);

  // Two concurrent calls both reach here with the same (now-about-to-be-invalidated) refresh token
  const response = await axios.post("https://provider.example.com/oauth/token", {
    grant_type: "refresh_token",
    refresh_token: refreshToken,  // Both requests use the same token
    client_id: process.env.OAUTH_CLIENT_ID,
  });

  // The first call's new refresh token is overwritten by the second call's
  // The second call may actually fail because the provider already invalidated
  // the refresh token when the first call used it — leaving the session with
  // no valid refresh token and requiring the user to re-authorize
  await redis.set(`session:${sessionId}`, JSON.stringify({
    accessToken: response.data.access_token,
    refreshToken: response.data.refresh_token,  // Race: may be overwritten or invalid
  }));
}
Part 6 — SkillAudit Detection

How SkillAudit's AST analysis detects each OAuth PKCE finding

SkillAudit's scanner builds a full AST for each TypeScript and JavaScript file in the MCP skill codebase, then applies taint-aware pattern matching across the OAuth flow paths. OAuth callback detection works by identifying route handlers that receive code and state as query parameters — a signature unique to OAuth callback endpoints — and then tracing the data flow forward to find the state validation, token exchange, and redirect calls.

Open redirect detection. The scanner identifies redirect calls (res.redirect(), res.writeHead(302)) where the target value is tainted by a query parameter from the OAuth callback request. If the taint path from req.query.* to a redirect destination is not broken by an allowlist or path-stripping transform, SkillAudit raises a REDIRECT3-like finding scoped to the OAuth callback context — catalogued as part of SA-SKL-OAUTH3.

Missing state validation detection. The scanner looks for OAuth callback handlers (identified by the code + state query parameter pattern and the presence of a token exchange HTTP call) where there is no comparison between req.query.state and req.session.*. The absence of any such comparison in the handler body is a direct finding. The scanner also checks ordering: if a token exchange call appears before the state comparison in control flow, it raises a "state validated after token exchange" finding at medium severity separately from the "state not validated at all" finding at critical severity.

Weak code_verifier entropy detection. The scanner traces the data flow to the code_verifier field in token exchange calls. If the verifier is derived from any of the following sources — Math.random(), Date.now(), uuid.v1(), uuid.v4() without an explicit note that the uuid package uses crypto.getRandomValues, or any string concatenation involving timestamps — it raises a high-severity finding. The acceptable source is crypto.randomBytes(n) with n >= 32, or the Web Crypto API equivalent crypto.getRandomValues(new Uint8Array(32)).

Token storage in localStorage detection. The scanner identifies localStorage.setItem() calls and checks whether any tainted value from the token exchange response (fields like access_token, refresh_token, token, id_token) flows into the storage call. This is a cross-file analysis because token exchange typically happens in a backend handler that emits the token to a frontend script via a JSON response — the scanner traces through the API boundary using type information and known response field names.

All four findings map to SA-SKL-OAUTH3 and affect the SkillAudit grade. See the SkillAudit vs Snyk comparison for how our OAuth-specific AST analysis differs from dependency-scanning approaches that only catch known CVEs in OAuth library dependencies rather than implementation-level misuse patterns.

Part 7 — Complete Fixed Implementation

Full OAuth PKCE implementation: randomBytes(32), SHA-256 challenge, early state validation, httpOnly cookies

The following is a complete, production-ready OAuth PKCE implementation for a Claude MCP skill's Express.js authorization server integration. It applies all four controls together: strong code_verifier entropy, early state validation with timing-safe comparison, no open redirect, and tokens stored only in server-side session behind an httpOnly cookie.

Complete Fixed Implementation
import express from "express";
import session from "express-session";
import RedisStore from "connect-redis";
import { createClient } from "redis";
import crypto from "crypto";
import axios from "axios";

const app = express();
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();

// Session configuration: httpOnly, Secure, SameSite=Strict
// Tokens are stored server-side in Redis — the browser only holds the session ID cookie
app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: process.env.SESSION_SECRET!,  // Must be a long, random secret
  resave: false,
  saveUninitialized: false,  // No session created before authentication
  genid: () => crypto.randomBytes(32).toString("hex"),
  name: "sid",  // Don't use the default 'connect.sid' — obscures the session library
  cookie: {
    httpOnly: true,          // JavaScript cannot read this cookie
    secure: true,            // Only sent over HTTPS
    sameSite: "strict",      // Not sent on cross-site requests (blocks CSRF)
    maxAge: 8 * 60 * 60 * 1000, // 8-hour session lifetime
  },
}));

// ─── /auth/start ─────────────────────────────────────────────────────────────
// Initiates the OAuth PKCE flow. Generates code_verifier and state,
// stores them in server-side session, and redirects to the authorization server.

app.get("/auth/start", (req, res) => {
  // Sanitize post-auth redirect destination to relative paths only
  const rawNext = typeof req.query.next === "string" ? req.query.next : "/dashboard";
  const safeNext = rawNext.startsWith("/") && !rawNext.startsWith("//")
    ? rawNext
    : "/dashboard";

  // Generate code_verifier: 32 bytes = 256 bits of cryptographic randomness
  // Base64URL encoding satisfies RFC 7636 unreserved character set (no padding needed)
  const codeVerifier = crypto.randomBytes(32).toString("base64url");

  // Derive code_challenge: BASE64URL(SHA256(ASCII(code_verifier)))
  // Always use S256 — never use 'plain', which provides no security benefit over no PKCE
  const codeChallenge = crypto
    .createHash("sha256")
    .update(codeVerifier, "ascii")
    .digest("base64url");

  // Generate state: 16 bytes = 128 bits for CSRF binding
  const state = crypto.randomBytes(16).toString("base64url");

  // Store code_verifier, state, and flow metadata in server-side session only
  // These values must NEVER be sent to the client or stored in cookies/localStorage
  req.session.oauthCodeVerifier = codeVerifier;
  req.session.oauthState = state;
  req.session.oauthStateCreatedAt = Date.now();
  req.session.postOAuthRedirect = safeNext;

  // Build authorization URL — code_challenge goes here, code_verifier does NOT
  const authUrl = new URL(process.env.OAUTH_AUTHORIZATION_ENDPOINT!);
  authUrl.searchParams.set("response_type", "code");
  authUrl.searchParams.set("client_id", process.env.OAUTH_CLIENT_ID!);
  authUrl.searchParams.set("redirect_uri", process.env.OAUTH_REDIRECT_URI!);
  authUrl.searchParams.set("scope", process.env.OAUTH_SCOPE ?? "read:user");
  authUrl.searchParams.set("state", state);
  authUrl.searchParams.set("code_challenge", codeChallenge);
  authUrl.searchParams.set("code_challenge_method", "S256");

  res.redirect(authUrl.toString());
});

// ─── /auth/callback ──────────────────────────────────────────────────────────
// Handles the authorization server's redirect. Validates state FIRST,
// exchanges code for tokens, stores tokens in server-side session only.

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

  // Handle authorization errors from the provider before anything else
  if (error) {
    const description = typeof error_description === "string"
      ? error_description
      : String(error);
    console.error("OAuth error from provider:", description);
    return res.status(400).send(`Authorization failed: ${description}`);
  }

  // ── STEP 1: Validate state parameter FIRST ──────────────────────────────
  // This must happen before the token exchange, before any database queries,
  // before any logging that includes the authorization code.
  // A CSRF attack delivers a code that was obtained by the attacker; the state
  // mismatch is the ONLY signal that this callback was not initiated by this session.

  if (
    typeof state !== "string" ||
    typeof req.session.oauthState !== "string" ||
    state.length !== req.session.oauthState.length ||  // timingSafeEqual requires equal lengths
    !crypto.timingSafeEqual(
      Buffer.from(state, "utf8"),
      Buffer.from(req.session.oauthState, "utf8")
    )
  ) {
    // Invalidate the session to prevent fixation and clear any partial state
    req.session.destroy(() => {});
    return res.status(403).send("Invalid OAuth state — possible CSRF attempt");
  }

  // Check state freshness: reject flows older than 10 minutes
  // A legitimate user completes the flow in seconds; a stale flow suggests replay
  if (Date.now() - (req.session.oauthStateCreatedAt ?? 0) > 10 * 60 * 1000) {
    req.session.destroy(() => {});
    return res.status(403).send("OAuth state expired — please start the authorization flow again");
  }

  if (typeof code !== "string" || code.length === 0) {
    return res.status(400).send("Missing authorization code");
  }

  // Retrieve code_verifier from server-side session — it was never sent to the browser
  const codeVerifier = req.session.oauthCodeVerifier;
  if (!codeVerifier) {
    return res.status(400).send("Missing code verifier — session may have expired");
  }

  // ── STEP 2: Exchange authorization code for tokens ───────────────────────
  let tokenData: {
    access_token: string;
    refresh_token?: string;
    expires_in?: number;
    token_type: string;
  };

  try {
    const tokenResponse = await axios.post(
      process.env.OAUTH_TOKEN_ENDPOINT!,
      new URLSearchParams({
        grant_type: "authorization_code",
        code,
        code_verifier: codeVerifier,  // Proof of the original authorization request
        client_id: process.env.OAUTH_CLIENT_ID!,
        redirect_uri: process.env.OAUTH_REDIRECT_URI!,
      }).toString(),
      {
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        timeout: 10_000,
      }
    );
    tokenData = tokenResponse.data;
  } catch (err) {
    console.error("Token exchange failed:", err);
    return res.status(502).send("Token exchange failed — please try again");
  }

  // ── STEP 3: Store tokens in server-side session, never in the browser ────
  // The access token and refresh token are stored ONLY in Redis via the session store.
  // The browser holds only the session ID cookie (HttpOnly; Secure; SameSite=Strict).
  // JavaScript on the page cannot read these tokens.
  req.session.accessToken = tokenData.access_token;
  req.session.tokenType = tokenData.token_type;
  req.session.tokenExpiresAt = tokenData.expires_in
    ? Date.now() + tokenData.expires_in * 1000
    : null;

  if (tokenData.refresh_token) {
    req.session.refreshToken = tokenData.refresh_token;
  }

  req.session.authenticated = true;
  req.session.authenticatedAt = Date.now();

  // ── STEP 4: Clear single-use PKCE and state values ───────────────────────
  // These values are now spent — delete them to prevent replay
  delete req.session.oauthCodeVerifier;
  delete req.session.oauthState;
  delete req.session.oauthStateCreatedAt;

  // ── STEP 5: Redirect to the pre-stored destination ───────────────────────
  // The destination was stored in session BEFORE the OAuth flow started,
  // not read from the callback URL — no open redirect possible
  const destination = req.session.postOAuthRedirect ?? "/dashboard";
  delete req.session.postOAuthRedirect;

  // Regenerate session ID after authentication to prevent session fixation
  req.session.regenerate((err) => {
    if (err) {
      console.error("Session regeneration failed:", err);
      return res.status(500).send("Session error");
    }
    // Re-attach authenticated data to the new session ID
    req.session.accessToken = tokenData.access_token;
    req.session.refreshToken = tokenData.refresh_token;
    req.session.authenticated = true;
    req.session.authenticatedAt = Date.now();
    req.session.save((saveErr) => {
      if (saveErr) {
        return res.status(500).send("Session save error");
      }
      res.redirect(destination);
    });
  });
});

// ─── Token refresh with mutex to prevent race conditions ─────────────────────
// If two concurrent requests arrive with an expired access token,
// only one should trigger a refresh; the other should wait for the result.
// Using a simple Redis-backed lock here — replace with Redlock for production clusters.

const refreshLocks = new Map<string, Promise<string>>();

async function getValidAccessToken(sessionId: string, session: Express.Session): Promise<string> {
  // If token is still valid with 60-second buffer, return it immediately
  if (session.tokenExpiresAt && Date.now() < session.tokenExpiresAt - 60_000) {
    return session.accessToken as string;
  }

  // If a refresh is already in flight for this session, wait for it
  const inFlight = refreshLocks.get(sessionId);
  if (inFlight) return inFlight;

  // Acquire the refresh lock for this session
  const refreshPromise = (async () => {
    try {
      const response = await axios.post(
        process.env.OAUTH_TOKEN_ENDPOINT!,
        new URLSearchParams({
          grant_type: "refresh_token",
          refresh_token: session.refreshToken as string,
          client_id: process.env.OAUTH_CLIENT_ID!,
        }).toString(),
        { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
      );

      // Update session with new tokens atomically
      session.accessToken = response.data.access_token;
      session.tokenExpiresAt = Date.now() + response.data.expires_in * 1000;
      if (response.data.refresh_token) {
        // Rotation: store new refresh token; old one is now invalid at the provider
        session.refreshToken = response.data.refresh_token;
      }
      await new Promise<void>((resolve, reject) => session.save((err) => err ? reject(err) : resolve()));

      return response.data.access_token as string;
    } finally {
      refreshLocks.delete(sessionId);
    }
  })();

  refreshLocks.set(sessionId, refreshPromise);
  return refreshPromise;
}

SA-SKL-OAUTH3 in your SkillAudit report? The finding maps to one or more of the patterns above. The remediation section of your report will show which pattern was detected — open redirect, missing state, weak entropy, or token storage — with the exact file and line number, the taint path our AST analysis followed, and a diff-ready fix suggestion. See the SA-SKL-OAUTH3 reference page for the complete finding taxonomy. For session management findings that may accompany OAuth issues, see SA-SKL-SESSION2.

Summary

OAuth PKCE findings: severity and grade impact

SA-SKL-OAUTH3 findings — grade impact
Critical No state parameter in OAuth callback — CSRF allows attacker to bind their authorization grant to victim session. −24 points.
Critical Open redirect in OAuth callback — attacker delivers crafted link that completes a legitimate flow but redirects the user to an attacker-controlled URL. −20 points.
Critical Access token or refresh token stored in localStorage — readable by any JavaScript on the page including third-party scripts and XSS payloads. −22 points.
High PKCE code_verifier derived from Math.random() or timestamp — insufficient entropy, brute-forceable from the visible code_challenge. −15 points.
High State parameter validated after token exchange — CSRF check too late; attacker's authorization code has already been consumed. −10 points.
High No session regeneration after OAuth authentication completes — session fixation attack possible (see SA-SKL-SESSION2). −12 points.
Medium Refresh token rotation without locking — concurrent token refresh can leave the session with an invalidated refresh token. −6 points.
Medium PKCE plain challenge method used instead of S256 — provides weaker binding and is not recommended by RFC 7636. −5 points.

OAuth PKCE implementation correctness is one of the highest-impact areas for MCP skill security because a broken OAuth flow can hand an attacker persistent API access to the third-party services the skill is authorized against — GitHub repositories, cloud storage, communication platforms, internal APIs — with the full scope the user granted. Getting the four controls right (entropy, state ordering, redirect allowlisting, token storage) closes the attack surface completely.

Run a SkillAudit scan to get SA-SKL-OAUTH3 findings across your entire MCP skill codebase, with per-file taint paths and diff-ready remediation for each pattern. For teams comparing options, see the SkillAudit vs Snyk comparison for how our OAuth implementation analysis differs from dependency-scanning approaches.