As the Model Context Protocol shifted from local stdio subprocesses to distributed Streamable HTTP servers, OAuth 2.1 became the backbone of enterprise MCP authentication. Yet implementing OAuth naively for MCP creates two severe vulnerability classes: confused-deputy token replay across MCP servers and Server-Side Request Forgery (SSRF) / credential redirection during OAuth metadata discovery.

This engineering guide explains how RFC 8707 (Resource Indicators), RFC 9728 (Protected Resource Metadata), and SSRF-safe discovery validation fit together — with a runnable Node.js verification module you can drop into your MCP clients and servers today.

How the Modern MCP OAuth 2.1 Flow Works

In the current MCP authorization specification, an MCP server acts strictly as an OAuth 2.1 Resource Server — never as a proxy that blindly forwards client tokens downstream (see MCP token passthrough anti-pattern):

  1. Challenge with Resource Metadata (RFC 9728): An unauthenticated MCP client calls the MCP endpoint and receives 401 Unauthorized with a WWW-Authenticate header pointing to /.well-known/oauth-protected-resource.
  2. Discover Authorization Server (RFC 8414): The client fetches the protected resource metadata, extracts the authorization_servers URI, and retrieves that authorization server's OAuth metadata (/.well-known/oauth-authorization-server or OIDC discovery).
  3. Request Audience-Bound Token (RFC 8707 + PKCE): During authorization and token exchange, the client sends the mandatory resource parameter set to the canonical URI of the target MCP server (for example, https://mcp-billing.internal.example.com/mcp) alongside PKCE S256.
  4. Strict Audience Enforcement on Every Call: The MCP server validates the JWT signature, issuer (iss), expiration (exp), required scopes, and — critically — confirms that the token's aud claim exactly matches its own canonical resource URI.

Threat 1: Why Skipping RFC 8707 Causes Confused-Deputy Replay

Imagine your enterprise runs two MCP servers behind the same Identity Provider (Okta, Microsoft Entra ID, or Keycloak):

  • https://mcp-docs.example.com/mcp (low-privilege public documentation search)
  • https://mcp-finance.example.com/mcp (high-privilege invoice and refund server)

If your MCP client omits the RFC 8707 resource parameter — or if mcp-finance only checks the JWT signature and iss without checking aud — an attacker who compromises mcp-docs (or obtains a token scoped for mcp-docs) can replay that valid IdP-signed token directly against mcp-finance.

Check What Happens If Missing Mandatory Hardening
RFC 8707 resource param IdP mints a broad multi-resource access token Client must send canonical MCP server URI in both /authorize and /token requests
Exact JWT aud match Cross-server token replay (confused deputy) Resource server rejects any token whose aud does not strictly equal its own canonical URI
No token passthrough Downstream APIs accept tokens not minted for them MCP server exchanges or mints separate least-privilege downstream credentials
Transport separation Local stdio servers leak browser OAuth redirects Never run web OAuth flows over stdio; use scoped runtime credentials or a gateway

Threat 2: OAuth Discovery SSRF & Malicious Token-Endpoint Redirects

Automatic discovery via RFC 9728 (oauth-protected-resource), RFC 8414 (oauth-authorization-server), and Dynamic Client Registration (DCR) is convenient for developer onboarding — and dangerous if an MCP client blindly fetches any URL handed to it by an untrusted remote MCP server:

  • Internal Network SSRF: A malicious remote MCP server returns WWW-Authenticate: Bearer resource_metadata="http://169.254.169.254/latest/meta-data/" or http://10.0.0.15:8080/admin. A naive client fetches that URL from inside your corporate VPC or Kubernetes pod.
  • Authorization Code / Secret Exfiltration: A compromised MCP server advertises an attacker-controlled token_endpoint in its authorization server metadata. If the client skips issuer/origin allow-listing, it sends the user's authorization code, PKCE verifier, or client secret directly to the attacker.

Runnable Node.js Validator: SSRF-Safe Discovery + RFC 8707 aud Check

Use this zero-dependency Node.js 20+ module on your MCP clients (before fetching discovery metadata) and on your MCP resource servers (when enforcing RFC 8707 audience binding):

// mcp-oauth-guard.mjs — SSRF-safe RFC 9728/8414 URL guard & RFC 8707 aud check
import dns from "node:dns/promises";
import net from "node:net";

const ALLOWED_ISSUER_ORIGINS = new Set([
  "https://auth.example.com",
  "https://login.microsoftonline.com",
]);

function isPrivateOrLinkLocalIp(ip) {
  if (net.isIPv4(ip)) {
    const [a, b] = ip.split(".").map(Number);
    return (
      a === 10 ||
      a === 127 ||
      a === 0 ||
      (a === 169 && b === 254) || // cloud metadata / link-local
      (a === 172 && b >= 16 && b <= 31) ||
      (a === 192 && b === 168) ||
      (a === 100 && b >= 64 && b <= 127) // CGNAT
    );
  }
  const lower = ip.toLowerCase();
  return (
    lower === "::1" ||
    lower.startsWith("fc") ||
    lower.startsWith("fd") ||
    lower.startsWith("fe80:") ||
    lower.startsWith("::ffff:127.") ||
    lower.startsWith("::ffff:169.254.") ||
    lower.startsWith("::ffff:10.")
  );
}

/**
 * Validate any OAuth discovery or token URL before fetching to stop SSRF
 * and attacker-controlled authorization server hijacking.
 */
export async function assertSafeOAuthUrl(rawUrl, { requireAllowedIssuer = false } = {}) {
  const url = new URL(rawUrl);
  if (url.protocol !== "https:") {
    throw new Error(`Rejected non-HTTPS OAuth URL: ${url.protocol}`);
  }
  if (url.username || url.password) {
    throw new Error("Rejected OAuth URL containing embedded credentials");
  }
  if (requireAllowedIssuer && !ALLOWED_ISSUER_ORIGINS.has(url.origin)) {
    throw new Error(`Untrusted OAuth issuer origin: ${url.origin}`);
  }
  const records = await dns.lookup(url.hostname, { all: true });
  if (!records.length) {
    throw new Error(`DNS resolution failed for ${url.hostname}`);
  }
  for (const { address } of records) {
    if (isPrivateOrLinkLocalIp(address)) {
      throw new Error(`Blocked SSRF target IP (${address}) for ${url.hostname}`);
    }
  }
  return url.toString();
}

/**
 * Enforce RFC 8707 Resource Indicator audience binding on an MCP Resource Server.
 * Call after verifying the JWT cryptographic signature, iss, exp, and nbf.
 */
export function assertRfc8707Audience(verifiedJwtClaims, canonicalMcpResourceUri) {
  const aud = verifiedJwtClaims?.aud;
  const normalizedTarget = new URL(canonicalMcpResourceUri).href.replace(/\/$/, "");
  const audiences = Array.isArray(aud) ? aud : typeof aud === "string" ? [aud] : [];

  const exactMatch = audiences.some((entry) => {
    try {
      return new URL(entry).href.replace(/\/$/, "") === normalizedTarget;
    } catch {
      return false;
    }
  });

  if (!exactMatch) {
    throw new Error(
      `RFC 8707 audience mismatch: token aud [${audiences.join(", ")}] does not match ${normalizedTarget}`
    );
  }
}

Additional Production Hardening Notes

  • Disable automatic HTTP redirects on discovery fetches (redirect: "manual"): Otherwise an allow-listed external domain can 302 redirect your HTTP client straight to http://169.254.169.254/.
  • Pin DNS resolution to the checked IP (or route through an egress proxy): Prevents DNS rebinding between dns.lookup() and the actual TCP socket connection.
  • Verify resource metadata matches the server you called: Under RFC 9728, the resource field inside /.well-known/oauth-protected-resource must match the MCP endpoint URI the client originally connected to.
  • Audit existing configs and errors: Pair this check with MCP OAuth 401/403 troubleshooting and OWASP MCP Top 10 (MCP01–MCP10).

How a Central MCP Gateway Simplifies OAuth Across Every Server

Asking twenty internal product teams to implement RFC 8707, RFC 9728, PKCE, SSRF-safe discovery, and tool-level scopes without a single bug is fragile. Centralizing MCP connections behind a governed MCP gateway lets platform teams enforce authentication, per-connection tool allow-lists, argument guardrails, and rate limits in one place — while keeping upstream credentials encrypted server-side.

Praesidia records the decisions it makes on governed MCP tool calls routed through it in an append-only, hash-chained audit trail with offline verification. Test your existing mcp.json configurations locally with the MCP config security checker or score all ten protocol controls with the OWASP MCP Top 10 checklist.

Common questions

Why is RFC 8707 mandatory in modern MCP OAuth implementations? RFC 8707 (Resource Indicators) binds an OAuth access token to one exact MCP server URI via the resource parameter and JWT aud claim. Without it, a valid token minted by your enterprise identity provider for a low-risk MCP server can be replayed against a high-privilege MCP server in a confused-deputy attack.

How does OAuth discovery create an SSRF risk for MCP clients? Under RFC 9728 and RFC 8414, an MCP server directs clients to metadata and token-endpoint URLs. If an MCP client fetches arbitrary URLs from an untrusted remote server without enforcing HTTPS, disabling redirects, blocking RFC 1918 / link-local IPs (169.254.169.254), and allow-listing trusted issuer origins, an attacker can probe internal cloud services or steal authorization codes.

Should local stdio MCP servers use OAuth 2.1 browser flows? No. Local stdio transports should not run interactive browser OAuth discovery flows; they should either receive narrowly scoped runtime credentials from a secure credential store or connect through an authenticated corporate MCP gateway that terminates OAuth cleanly over HTTPS.

Can an MCP server pass the caller's OAuth access token straight to a downstream API like GitHub or Salesforce? No — that is the token passthrough anti-pattern (MCP07). Downstream APIs should never receive an access token minted for the MCP server's audience; instead, the MCP server or gateway must validate the incoming token's audience and obtain a separately scoped downstream credential.