Authenticating a remote MCP server with OAuth 2.1 — Guide
MCP Engineering course · M3
This guide is the printable companion to lesson L13. It covers the current protocol (revision 2026-07-28, Authorization): the roles, the full flow with PKCE and the resource parameter, how a server validates a token, why token passthrough is forbidden, and what changes between the local lab and a real deployment.
What changed in V2: the earlier version of this guide used a five-step "401 → discovery → token → validate" flow, said every token is a JWT and that OAuth 2.1 is "required", and cited video timestamps. V2 adds the mandatory steps (authorization-server metadata, client registration, PKCE,resource,isscheck), the no-passthrough rule and the 403 step-up, and is tied to a lab you run (lab-l13), not to the video.
First: when does this apply?
Authorization is OPTIONAL in MCP. Servers using an HTTP transport SHOULD follow the authorization spec, whose framework is OAuth 2.1. Servers using stdio SHOULD NOT; they read credentials from the environment. So this guide is about remote (HTTP) servers that need to know who is calling. If a remote server handles private data or actions, treat authorization as required in practice: an unauthenticated URL is open to anyone who can reach it.
The roles
| Role | Who | Job |
|---|---|---|
| Resource server | your MCP server | publishes its metadata, validates every token, enforces scope |
| OAuth 2.1 client | the MCP client in the host | discovers, registers, runs PKCE, presents the token |
| Authorization server | an identity provider | authenticates the user, records consent, issues tokens |
The user authenticates and consents; the client is usually a public client protected by PKCE, not something that "proves its identity" with a secret.
The flow, step by step
- The client calls the server without a token. The server answers 401 with
WWW-Authenticate: Bearer ... resource_metadata="<url>". - The client fetches that Protected Resource Metadata document (RFC 9728). MCP servers MUST publish it. It names the resource (this server's canonical URI) and its authorization server(s).
- The client reads the authorization server's metadata (RFC 8414 or OpenID Connect discovery) and records the
issuer. Ifcode_challenge_methods_supportedis missing, the client MUST refuse to continue. - The client needs a client ID. In priority order: pre-registered credentials; then Client ID Metadata Documents (CIMD), if the server advertises
client_id_metadata_document_supported; then Dynamic Client Registration (deprecated fallback); last, asking the user. - The client sends the user's browser to
/authorizewith a PKCE challenge (S256whenever it can) and theresourceparameter (RFC 8707). On return, it checksstateand checksissagainst the recorded issuer (RFC 9207), which defends against mix-up attacks. - The client exchanges the code at
/token, sending thecode_verifierandresourceagain.resourceMUST be in both the authorization request and the token request. - The client calls the MCP server with
Authorization: Bearer <token>on every request, and never in the query string.
What the server must do with a token
| Check | Failure response |
|---|---|
| Signature (or introspection, for opaque tokens) | 401 |
| Issuer = the one trusted authorization server | 401 |
Audience = this server (the resource it was issued for) | 401 |
| Expiry | 401 |
| Scope sufficient for the request | 403 with error="insufficient_scope"; the client can ask for more scope (step-up) |
Tokens need not be JWTs: they are often JWTs, but may be opaque and checked by introspection. The lab uses JWTs.
Never pass tokens through. The spec says: "MCP servers MUST NOT accept or transit any other tokens." Your server accepts only tokens issued for itself, and if a tool calls another API, it uses its own credential for that API (or a token obtained for that API). It never forwards the client's bearer token upstream.
Worked example: the lab's resource server (lab-l13)
Official Python SDK, pinned mcp==2.3.0 (with pyjwt[crypto] 2.15.1, cryptography 50.0.2, starlette 1.10.0, uvicorn 0.54.0, httpx2 2.16.2, all in uv.lock). From protected_server.py:
auth = AuthSettings(
issuer_url=ISSUER,
resource_server_url=RESOURCE_URL,
required_scopes=["notes:read"],
validate_token_resource=True, # default in 2.3.0 is None (warn only): turn it on explicitly
)
resource_server_url makes the SDK publish the RFC 9728 document at /.well-known/oauth-protected-resource/mcp and send the 401 with resource_metadata.
SDK caveat: in mcp 2.3.0,validate_token_resourcedefaults toNone, which only logs a warning and behaves asFalse. Leave it unset and the SDK's audience gate is off. Turn it on.
The lab also checks the token itself:
claims = jwt.decode(
token,
key=key,
algorithms=["RS256"], # never accept "none" or HS* here
audience=self.audience, # RFC 8707 / spec: accept only tokens issued for this server
issuer=self.issuer,
options={"require": ["iss", "aud", "exp", "iat", "sub"]},
)
The upstream call uses the server's own credential:
# NO TOKEN PASSTHROUGH: the upstream gets the server's own credential, never the client's token.
headers = {"Authorization": f"Bearer {UPSTREAM_SERVICE_TOKEN}"}
add_notealso needsnotes:write, checked inside the tool withget_access_token(): a read-only token gets a tool result withisError, not an HTTP 403. The spec's 403 step-up is what the SDK applies per endpoint (required_scopes).- SDK gap on the authorization-server side: in mcp 2.3.0, the SDK's
/tokenhandler parsesresourcebut does not pass it to the provider. The lab's test authorization server wraps it (TokenResourceCheck) to requireresourceand match it to the/authorizevalue.
CIMD, and why the lab pre-registers its client
With CIMD, the client_id is itself an HTTPS URL with a path (for example https://app.example.com/oauth/client-metadata.json). The authorization server fetches the JSON at that URL, checks that its client_id matches the URL exactly, and checks its redirect_uris. Clients and authorization servers SHOULD support CIMD. The lab runs only on loopback and cannot host a public HTTPS document, so it uses a pre-registered client with DCR off. CIMD is explained, not run.
Run it
cd lab-l13
./run.sh verify # uv sync --locked, starts the test AS (9000), the MCP server (8000), the upstream (8002)
./run.sh serve # leave them running, then:
curl -i -X POST http://127.0.0.1:8000/mcp -H 'content-type: application/json' -d '{}'
curl http://127.0.0.1:8000/.well-known/oauth-protected-resource/mcp
- The run ends with
ALL CHECKS PASSED (49). - A1 shows
HTTP 401withresource_metadata="http://127.0.0.1:8000/.well-known/oauth-protected-resource/mcp". - A5 shows
aud=http://127.0.0.1:8000/mcp; A7 showsPASS A7 upstream NEVER received the client's token (no passthrough). - Section B: the SDK client requested
code_challenge_method=S256andresource=http://127.0.0.1:8000/mcp. - Section C lists refused attacks: wrong audience → 401 (C1); missing scope → 403
insufficient_scope(C2); no PKCE,plain, wrong or missing verifier, reused code, missing/unknown/mismatchedresource(C4, C5); expired, forged, wrong-issuer andalg=nonetokens → 401 (C6, C7); token in the query string refused (C8); the SDK's warn-only default detected (C9); foreignOrigin→ 403 (C10).
Local practice versus a real deployment
| In the lab (test-only) | In a real deployment |
|---|---|
| Plain HTTP on 127.0.0.1 | TLS everywhere. AS endpoints MUST be HTTPS; redirect URIs MUST be localhost or HTTPS |
Automatic consent for learner-001, no login | Real user login, a consent screen, exact redirect_uri matching |
| Ephemeral signing key | Managed keys with rotation, published through JWKS |
| Pre-registered client in code | CIMD or pre-registration; avoid DCR |
resource_server_url is a loopback URL | The public HTTPS URL, with Origin/Host allow-lists for that hostname |
Never deploy test_auth_server.py. Keep tokens short-lived and never log them.
To remember
- Authorization is optional; HTTP servers SHOULD follow it (OAuth 2.1); stdio servers use the environment.
- Flow: 401 → RFC 9728 metadata → AS metadata → client ID (pre-registered / CIMD) → PKCE S256 +
resource→ token (resourceagain) → Bearer on every request. - Validate signature, issuer, audience, expiry, scope; insufficient scope = 403
insufficient_scope. - No token passthrough: accept only tokens for yourself; use your own credential upstream.
- In mcp 2.3.0, set
validate_token_resource=True(the default only warns).
Turning Point Academy · MCP Engineering course · Module 3 · Lesson 13 (L13) · V2, spec 2026-07-28