Catalog My learning Blog
Build AI Agents with MCP: 30-Day Course · Phase 5 · Lesson 22 · 5 min read

MCP Authorization with OAuth 2.1 Explained

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Python Server as an OAuth Resource Server
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain how a remote MCP server authorizes clients with OAuth 2.1: protected resource metadata, authorization server discovery, PKCE, audience-bound tokens, client registration with Client ID Metadata Documents, and scopes. Configure a server as an OAuth resource server and avoid the token passthrough anti-pattern.

Concept Explanation

A remote MCP server that exposes real data needs to know who is calling and what they may do. MCP standardizes this on OAuth 2.1, with a clear division of roles. The MCP server is an OAuth resource server: it accepts access tokens and checks them. A separate authorization server, often your existing identity provider such as Auth0, Okta, Entra ID or Keycloak, authenticates the user and issues tokens. The MCP client, inside the host, is the OAuth client that obtains tokens on the user's behalf. Keeping the MCP server out of the business of issuing tokens is what lets it plug into existing identity infrastructure.

The flow starts with a refusal. A client calls the server without a token and receives HTTP 401 with a WWW-Authenticate header that includes a resource_metadata URL. That URL serves Protected Resource Metadata, defined in RFC 9728: the resource identifier of the server and the authorization servers it trusts, plus supported scopes. The client then reads the authorization server's own metadata (RFC 8414 or OpenID Connect discovery) to find its authorization and token endpoints. It runs the authorization code flow with PKCE, which OAuth 2.1 requires for all clients, so a stolen authorization code is useless without the original verifier. The user signs in and consents in the browser, and the client receives an access token.

Clients must request tokens for this specific server by passing the resource parameter from RFC 8707, and servers must reject tokens issued for a different audience. This audience binding prevents a token minted for one MCP server from being replayed against another. For the same reason, an MCP server must never pass the client's token through to upstream APIs. If the server needs to call GitHub or a payment API, it obtains its own token for that API, for example through a token exchange or its own OAuth flow. Token passthrough creates a confused deputy: the upstream API cannot tell whether the request was authorized for it, and audit trails break.

How does an authorization server know about a client it has never seen, such as a new desktop app? Earlier revisions used Dynamic Client Registration, where clients registered themselves at run time. The specification now prefers Client ID Metadata Documents: the client's id is an HTTPS URL that serves a JSON document describing the client, its name and redirect URIs, so the authorization server can fetch and verify it without a registration step. Dynamic Client Registration is deprecated as of 2026-07-28 but still supported for compatibility. Clients must also validate the iss parameter in authorization responses (RFC 9207) to defeat mix-up attacks.

Scopes express what a token allows, such as invoices:read. A server can require scopes globally and check them per tool, and when a call needs more than the token grants it can respond with an insufficient_scope challenge so the client asks the user to approve the additional permission.

StepStandardWhat happens
401 challengeRFC 9728WWW-Authenticate points to protected resource metadata
Discover authorization serverRFC 8414, OpenID ConnectClient finds authorization and token endpoints
Identify the clientClient ID Metadata Documents (DCR deprecated)Client id is a URL to its metadata
AuthorizeOAuth 2.1 code flow with PKCE, RFC 9207 iss checkUser signs in and consents
Request token for this serverRFC 8707 resource indicatorToken audience is the MCP server
Call toolsBearer token on every requestServer validates audience, expiry and scopes

Worked Example: A Python Server as an OAuth Resource Server

The server below accepts only tokens issued for its own URL with the invoices:read scope. The verifier is a stand-in for real JWT validation against your authorization server's signing keys.

Python
import time
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

RESOURCE = "https://billing.example.com/mcp"

class JwtVerifier:
    async def verify_token(self, token: str) -> AccessToken | None:
        claims = validate_jwt(token, jwks_url="https://auth.example.com/.well-known/jwks.json",
                              audience=RESOURCE)            # signature, expiry, audience
        if claims is None:
            return None
        return AccessToken(token=token, client_id=claims["azp"], scopes=claims["scope"].split(),
                           expires_at=claims["exp"], resource=RESOURCE, subject=claims["sub"])

mcp = MCPServer(
    "billing",
    token_verifier=JwtVerifier(),
    auth=AuthSettings(issuer_url="https://auth.example.com", resource_server_url=RESOURCE,
                      required_scopes=["invoices:read"], validate_token_resource=True),
)

@mcp.tool()
def my_invoices() -> list[str]:
    """List the signed-in user's invoices."""
    token = get_access_token()
    if token is None or "invoices:read" not in token.scopes:
        raise ToolError("Missing scope invoices:read.")
    return INVOICES.for_user(token.subject)       # authorization uses the token's subject

app = mcp.streamable_http_app()

A request without a token now gets 401 with a header like the following, and the metadata document lists the trusted authorization server:

Code
WWW-Authenticate: Bearer error="invalid_token", error_description="Authentication required",
    resource_metadata="https://billing.example.com/.well-known/oauth-protected-resource/mcp"

GET /.well-known/oauth-protected-resource/mcp
{"resource":"https://billing.example.com/mcp","authorization_servers":["https://auth.example.com"],
 "scopes_supported":["invoices:read"],"bearer_methods_supported":["header"]}

The tool filters invoices by the token's subject rather than by any argument, so a model cannot ask for another user's invoices.

An unauthenticated call gets 401 pointing to protected resource metadata. The client discovers the authorization server, runs the code flow with PKCE, requests a token bound to this server, then calls tools with it.
An unauthenticated call gets 401 pointing to protected resource metadata. The client discovers the authorization server, runs the code flow with PKCE, requests a token bound to this server, then calls tools with it.

Real-World Examples

  • The MCP authorization specification was rewritten in the 2025-06-18 revision to classify MCP servers as OAuth resource servers with RFC 9728 metadata, after the earlier design had required servers to act as their own authorization servers, which enterprises found impractical.
  • Hosted MCP servers from GitHub, Atlassian, Linear and others use OAuth so users connect with a browser sign-in instead of pasting long-lived API keys into configuration files.
Key TakeawaysA remote MCP server is an OAuth resource server, while a separate authorization server issues the tokens that clients present to it. Clients discover it through a 401 with protected resource metadata, use the code flow with PKCE, identify themselves with Client ID Metadata Documents, and request audience-bound tokens with resource indicators. Servers validate audience, expiry and scopes, authorize by the token's subject, and never pass client tokens through to upstream APIs.

Review Questions & Answers

The server answers an unauthenticated request with 401 and a WWW-Authenticate header pointing to its protected resource metadata, which lists the trusted authorization servers. The client then reads that authorization server's metadata to find its endpoints.

It binds the token's audience to a specific MCP server. Servers reject tokens issued for other audiences, so a token obtained for one server cannot be replayed against another.

The upstream API would accept a token that was not issued for it, creating a confused deputy and breaking audit and audience controls. The server should obtain its own credentials for upstream calls.

Authorization servers need to know about clients they have never seen. With CIMD the client id is an HTTPS URL to a metadata document the server can fetch, removing the need for Dynamic Client Registration, which is now deprecated.