MCP Server OAuth 2.0 Authorization Code Flow
A step-by-step guide to securing MCP servers with OAuth 2.1.

The MCP server authorization code flow uses OAuth 2.1 to establish user-delegated access without a custom login system. PKCE, metadata discovery, and bearer token validation are the protections that make the flow work. A server is correctly secured only when each handoff checks who issued the credentials, which server they belong to, and what access they permit.
Why MCP servers need a dedicated authorization layer
In local stdio deployments, the client and server run on the same machine, so there is no network boundary for this OAuth flow to protect. Remote HTTP changes that boundary. Requests can arrive from untrusted callers, so a protected MCP server needs validated, audience-bound tokens to distinguish authorized access from everything else. Static API keys and long-lived shared secrets offer a weaker basis for delegated access because an overly permissive compromised key can grant unrestricted tool access.
MCP makes authorization optional, but its authorization guide strongly recommends it for user-specific data, auditing, enterprise access controls, and per-user rate limits. Those conditions describe much of production use. OAuth 2.1 lets these deployments use existing identity providers and authorization servers.
The three roles every MCP OAuth implementation must keep separate
The MCP client is the OAuth client acting for a user. It starts authorization, opens the browser, stores the token, and sends that token with requests. The authorization server decides what access to grant, authenticates users, and issues tokens.
The MCP server is the OAuth resource server. It validates tokens, enforces scopes, and proxies permitted calls to an upstream API. Since the June 2025 revision, the architecture has explicitly allowed a separate authorization service, so the MCP server no longer has to run one.
These roles can be co-hosted without becoming interchangeable. The distinction is about responsibility. Protected resource metadata describes the MCP server, while authorization server metadata describes the issuer, and clients must fetch them separately. Collapsing those identities removes the clear reference points needed to check issuer and audience binding.
What the authorization code flow with PKCE actually does, step by step

First, the client sends a request without a token. The server responds with 401 Unauthorized. Its WWW-Authenticate header can include a resource_metadata parameter pointing to the Protected Resource Metadata document, or PRM. The server must provide that pointer or publish the document at a well-known URI.
Second, the client fetches the PRM document under RFC 9728. Its authorization_servers array must contain at least one entry. The resource identity must match exactly. For well-known discovery, the resource value must match the resource identifier used to construct the metadata URL. For discovery through the challenge header, it must match the URL the client used to contact the resource server.
Third, the client retrieves the authorization server’s metadata. Clients must support both RFC 8414 metadata and OpenID Connect Discovery URLs, trying them in the specified order. The document’s issuer must match the identifier used to construct the metadata URL. A mismatch stops the flow. The client must also refuse to proceed if code_challenge_methods_supported is absent, because the required PKCE support has not been established.
Fourth, the client obtains a client ID. The registration preference is existing pre-registration, then Client ID Metadata Documents, or CIMD, then Dynamic Client Registration, or DCR, with manual registration as a fallback. The revision changes that choice. The 2026-07-28 revision deprecates DCR in favor of CIMD, so DCR should not become the primary registration path.
Fifth, the client records the validated issuer before opening the browser to the authorization_endpoint. The request includes code_challenge, code_challenge_method=S256, and a resource parameter set to the MCP server’s canonical URL. That resource value establishes the intended audience. The 2026-07-28 revision makes S256 mandatory, so plain PKCE is not acceptable.
Sixth, the authorization server redirects back with code, state, and, when it supports RFC 9207, iss. The client compares iss with the recorded issuer without normalizing either value. Advertised support makes a missing iss unacceptable. A missing or mismatched state also requires rejection, and if validation fails, the client must not act on or display the returned error.
Seventh, the client sends the authorization code, PKCE verifier, and the same resource value to the token endpoint. It receives an access token and may receive a refresh token. Eighth, it sends the access token in the Authorization header using the Bearer scheme on every request, never in the query string. The MCP server checks signature, expiry, audience, and scope before forwarding the request. Each handoff supplies a required input for the next, so a failed issuer check cannot be repaired by a successful token exchange.
How the device authorization flow handles clients that cannot receive a browser redirect
Some clients cannot receive a browser redirect at all. Terminal sessions, remote coding environments, appliances, constrained shells, and certain hosted agent runners need another route. The device authorization flow under RFC 8628 provides one without requiring a redirect URI. The client obtains a device_code, user_code, and verification URI from the authorization server.
The user then authorizes access on a separate device. Meanwhile, the client polls the token endpoint until the user approves access or the code expires. This changes the interaction while leaving the access boundary unchanged. The MCP requirements retain PKCE and audience binding through the resource parameter. Once a token arrives, the same rules as in the browser-based flow apply to bearer token delivery and server-side validation.
What scope selection actually controls, and what it does not
Once a token can be issued, scope selection determines which permissions the client requests. The MCP authorization guide defines the selection order. If the 401 challenge names scopes, the client requests those. Otherwise, it requests everything listed in the PRM document’s scopes_supported field, and if that field is absent, it omits the scope parameter.
That fallback makes granular scope design especially important. Permission to read prices should not also give permission to write orders, and an agent allowed to write orders should not get access to HR tools. Scopes constrain access at the tool level. An agent allowed to read documents can still get data it should not have if the upstream resource server has no independent row-level or attribute-level controls.
Consent also needs a boundary in time. Permission to do a specific task does not always include permission to keep acting forever, so refresh token lifetime should match how long consent is meant to last. For additional permissions, the 2025-11-25 revision introduced incremental authorization mid-session. The authorization server re-prompts the user before expanding access.
This separation also explains the limited regulatory role of scopes. GDPR Article 5(1)(b) establishes purpose limitation, supported by Article 25’s data protection by design. Scope controls are a technical way to support that purpose beyond the explicit requirements of Articles 5 and 6 themselves. A customer-service deployment must not get HR access just because both tools use the same authorization system.
The failure modes that break a flow that looks correct on paper
Discovery is a trust boundary. CVE-2025-6514, rated CVSS 9.6, was a flaw in mcp-remote that allowed OS command injection and remote code execution through crafted input in the authorization_endpoint response URL. It shows why accepting an endpoint from discovery requires checking that the endpoint is safe to process.
The official MCP Python SDK had a separate endpoint-validation flaw. A malicious MCP server could redirect the OAuth flow to an attacker-controlled endpoint that captured client secrets, authorization codes, and PKCE proof keys. Issuer validation guards against another failure, the mix-up attack. Omitting the RFC 9207 check leaves the client without the required confirmation that the authorization response came from the issuer it recorded.
Registration can break the same chain of trust. The Square MCP server allowed dynamic registration without redirect URI restrictions and used a shared static client ID when redirecting to Square’s authorization server. That undermined the client identity guarantee. At the subsequent authorization and token steps, missing PKCE leaves code interception open, while omitting resource from either request breaks audience binding.
Token passthrough is the corresponding failure at the resource server. It happens when the MCP server forwards the inbound user token unchanged to a downstream API without obtaining its own downstream token. That breaks audience restriction and exposes the token’s permissions to a compromised intermediary. Fudan’s study found that the majority of OAuth-enabled MCP servers studied acted as OAuth clients to upstream services, with cross-layer OAuth flaws documented in that subset.
Enterprise-managed authorization and the IdP delegation pattern
Enterprise-managed authorization, or EMA, makes organizational policy the basis for access rather than separate user consent screens for every connector. EMA reached stable status on June 18, 2026. Okta was the first supported identity provider, with Anthropic, Visual Studio Code, and seven MCP servers supporting it at launch. The architectural change is delegation to the organization’s IdP.
The user signs in through normal corporate SSO. The MCP client then uses OAuth Token Exchange to request an Identity Assertion JWT Authorization Grant, or ID-JAG. The IdP applies administrator-configured policies governing which servers the user’s role or group may reach, then issues a signed identity assertion JWT. Access decisions are recorded in the IdP’s admin console, creating one auditable trail across connectors.
Without an interactive choice between enterprise and personal grants, that step cannot accidentally route work data through a personal account. With federation upstream of the OAuth grant, corporate policies for MFA, session duration, and attribute mapping can apply. A gateway adds a point where access rules are enforced as requests reach the MCP deployment.
The gateway pattern as the enforcement layer for multi-server MCP deployments
Per-server OAuth configuration becomes harder to keep consistent as deployments grow. A gateway makes enforcement a shared function. Clients connect to a single gateway URL, which routes tool calls to backend servers while centralizing token validation, scope enforcement, and audit logging. Its OAuth integration handles issuance through the authorization-server role.
The gateway can also enforce per-team and per-role tool policies and log invocations with user identity and timestamp. Data loss prevention extends that boundary to inputs and outputs. Those rules also control what data passes through a tool call that is allowed, which scopes alone do not do. Real-time visibility provides signals for detecting anomalous calls, rather than leaving only a log to examine after an incident.
Tyk Gateway 5.14 implements this pattern through OAuth proxying, PRM mirroring, and scope enforcement for tools, resources, and prompts. MCP Manager is another option that puts a gateway in front of connected servers so they share authorization checks and access policy, with a server registry and a real-time view of what agents do. The registry closes a separate governance gap. Servers outside it remain unaccounted for and can bypass controls applied correctly to registered deployments.
What correct implementation requires the builder to verify before shipping
Before shipping, the builder should test rejection paths with as much care as a successful login. Start with an unauthenticated request and check for a usable metadata discovery route through the challenge header or well-known URI. Fetch the PRM document and compare its resource identity exactly with the required URL. A mismatched document must not be accepted.
Next, test authorization server discovery through the metadata routes it supports. Confirm that issuer matching rejects an incorrect identifier and that code_challenge_methods_supported includes S256. Test a request without a code challenge. It must fail, and a flow must also be rejected as not audience-bound if resource is removed from either the authorization request or the token request.
Then test the return from the browser. Check that the client records the issuer before authorization, compares iss without normalization, and rejects a missing value when RFC 9207 support was advertised. Missing or mismatched state must also fail. For registration, use existing pre-registration where it is available and otherwise default to CIMD, as DCR is deprecated.
Finally, test the server with tokens that fail signature, expiry, audience, or scope checks, and confirm that none reaches the upstream API. Confirm header-based bearer delivery, block inbound-token passthrough, and check that downstream calls use a separate token. Review granular scopes and refresh token lifetime against the intended task, and test device authorization where redirects are unavailable. Most of these checks pass or fail, so they show before deployment whether the protection works or only looks as though it does.


