使用 OAuth 授权客户端

阅读约需 126分钟 分钟,9节中含7个示例。

版次 2026.11.14 示例于 2026年11月19日 通过 70个示例中有70个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.14。 阅读原文

读完本章,你将能够用 OAuth 保护商店的 Model Context Protocol 服务器。你会发布引导客户端找到授权服务器的元数据,用客户端 ID 元数据文档(Client ID Metadata Document)标识客服团队的主机,通过 PKCE 获取令牌,只接受为商店服务器签发的令牌,借助每个响应中的签发者识别混淆攻击(mix-up attack),并为每个工具要求一个作用域,在退款需要更多权限时进行升级授权(step-up)。本章的论断以规范 2026-07-28 修订版为准,也就是 Python SDK mcp 2.3.0 所实现的版本。

通过 Streamable HTTP 提供服务把 shop-support 迁移到了一个 HTTP 地址上,以便客服人员的各个主机共用它。也就是商店的客服人员查看订单和办理退款所用的服务器。该服务器的 Origin 检查只能挡住网页,其他一概挡不住:任何能连上该端口的程序都可以读取订单和办理退款(见拒绝来自其他来源的请求)。因此,商店需要知道是哪台主机在调用、代表哪个人、以及这个人可以做什么。客服人员可以读取订单和库存;只有客服主管可以退款。

Model Context Protocol(MCP)的答案是 OAuth 2.1。MCP 中的授权是可选的,并且属于 HTTP 传输:stdio 服务器改为从环境中获取凭据(见授权)。受保护的 MCP 服务器是 OAuth 资源服务器,主机用于访问它的客户端是 OAuth 客户端,由授权服务器签发令牌,授权服务器可以与 MCP 服务器部署在一起,也可以分开部署。你在使用其他 API 时已经从客户端一侧了解过这一流程。MCP 带来的变化是,客户端事先对服务器一无所知。它只从一个 URL 出发,因此发现、客户端的身份和令牌的受众都必须在双方没有任何预先设置的情况下正常工作。

examples/lib/ 中的四个共享模块承载本章的准备工作,因此每个示例只展示其核心思路:

  • lib.auth_server 是商店的授权服务器,运行在回环地址上:提供元数据、带 PKCE 的授权码授权,在每个应答中返回 iss,并签发绑定到某一服务器的 JWT 访问令牌。授权同意是脚本化的,代替在浏览器前操作的人。它只是供这些回环示例使用的教学服务器,绝不能部署。它不对任何人进行登录认证,其签名密钥由本书公开的种子派生,因此任何拿到本书的人都能铸造它接受的令牌。实际部署应使用满足本章各项检查的成熟授权服务器。Python SDK 自带授权服务器,但其文档不建议新服务器使用,并且它的元数据既没有声明 iss,也没有声明客户端 ID 元数据文档(见 SDK 授权文档)。
  • lib.oauth_client 是主机一侧:SDK 的 OAuthClientProvider,使用内存中的令牌存储,外加一个脚本化的浏览器,它跟随授权服务器的重定向,并把应答交还给 SDK。
  • lib.tool_scopes 添加了 SDK 所没有的按工具作用域检查。
  • lib.protected_shop 把它们组合起来:第 3 章的五个工具置于 OAuth 之后,保持本章结束时的样子。

所有示例都通过明文 HTTP 运行在 127.0.0.1 上。这仅适用于本地开发。在生产环境中,授权服务器的每个端点都必须通过 HTTPS 提供服务(见安全注意事项)。

这部分尚未翻译,因此以英文显示。

Find the authorization server from the resource

最近一次修改见于版次 2026.11.11

A client that has only a server's URL must learn from the server where to get a token, and the pinned revision does this in two steps. First, MCP servers MUST publish Protected Resource Metadata (RFC 9728), a JSON document that names the resource and lists at least one authorization server (authorization). A request without a token gets 401, and its WWW-Authenticate header points to that document in a resource_metadata parameter. A client that finds no such parameter tries the well-known URI, /.well-known/oauth-protected-resource with the server's path inserted, and then without the path (authorization server discovery). Second, the client fetches the authorization server's own metadata (RFC 8414), which lists its endpoints and what it supports.

Two values must match along the way. The resource in the server's metadata must be identical to the URL the client used, or the client must not use the metadata (RFC 9728, section 3.3). And the issuer in the authorization server's metadata must be identical to the issuer the client built the well-known URL from (RFC 8414, section 3.3). Both checks stop a client from trusting a document that describes some other server.

The shop's server states its own URL, and the authorization server states its issuer. The SDK does the server's half when you give MCPServer an AuthSettings and a token verifier: issuer_url names the authorization server, resource_server_url is the server's own endpoint URL, and required_scopes lists the scopes every request needs. The shop's server requires orders:read and stock:read, because every ticket needs one or both. refunds:write comes later, and only when a refund needs it. The token verifier is lib.auth_server.JwtVerifier, which checks a token's signature, issuer and expiry. On loopback the port, and so the resource URL, is known only once the socket is open. So the server is built in a function of its base URL, and serve_built from lib.auth_server opens the socket first. Then the example plays a client: it sends tools/list with no token and follows the answer.

discover-the-authorization-server.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Protect the shop's server with OAuth, then follow its 401 to the authorization server, as a client does. The pointrests on the challenge's error line and on the PKCE methods line; the asserts check the rest of the chain."""from urllib.parse import urlsplitimport httpx2from mcp.server.auth.settings import AuthSettingsfrom lib import auth_server, http_mcp, shop_toolsdef protected(issuer: str):    def build(base_url: str):                                   # the server must know its own URL: the resource        settings = AuthSettings(issuer_url=issuer, resource_server_url=base_url + "/mcp",                                required_scopes=["orders:read", "stock:read"], validate_token_resource=True)        verifier = auth_server.JwtVerifier(issuer)        return shop_tools.create_server(version="0.8.0", auth=settings, token_verifier=verifier).streamable_http_app()    return buildwith auth_server.serve() as issuer, auth_server.serve_built(protected(issuer.url)) as base_url:  # the socket opens before the app is built, so the app knows its URL    first = http_mcp.post(base_url + "/mcp", "tools/list")                     # no token    print("status:", first.status_code)    # [7:] drops the scheme, "Bearer ", which is 7 characters; the values that follow are quoted    challenge = dict(part.split("=", 1) for part in first.headers["www-authenticate"][7:].split(", "))    print("challenge parameters:", ", ".join(challenge))    print("challenge error:", challenge["error"].strip('"'))    metadata_url = challenge["resource_metadata"].strip('"')    print("resource metadata path:", urlsplit(metadata_url).path)    resource = httpx2.get(metadata_url).json()    assert resource["resource"] == base_url + "/mcp"                            # RFC 9728: the endpoint's own URL    print("authorization servers:", len(resource["authorization_servers"]))    print("scopes_supported:", " ".join(resource["scopes_supported"]))    found = resource["authorization_servers"][0]                                # the one server the metadata lists    metadata = httpx2.get(found + "/.well-known/oauth-authorization-server").json()    assert metadata["issuer"] == found                                          # RFC 8414: the URL it was fetched from    print("code_challenge_methods_supported:", metadata["code_challenge_methods_supported"])    assert metadata["client_id_metadata_document_supported"]                    # the server advertises metadata documents    assert metadata["authorization_response_iss_parameter_supported"]           # and iss on every authorization response
输出python discover-the-authorization-server.py
status: 401
challenge parameters: error, error_description, resource_metadata
challenge error: invalid_token
resource metadata path: /.well-known/oauth-protected-resource/mcp
authorization servers: 1
scopes_supported: orders:read stock:read
code_challenge_methods_supported: ['S256']

The first request got 401, with a challenge carrying error, error_description, resource_metadata and the error invalid_token. That error is the SDK's choice, and a departure from RFC 6750, which says a server SHOULD NOT include an error code when a request carries no credentials at all (RFC 6750, section 3.1).

The metadata URL's path is /.well-known/oauth-protected-resource/mcp, the well-known prefix with the server's path inserted, as RFC 9728 asks. The metadata names the endpoint's own URL as its resource, lists 1 authorization server, and gives scopes_supported as orders:read stock:read, which the SDK fills from required_scopes.

The challenge has no scope parameter, because the SDK's 401 never sends one (mcp/server/auth/middleware/bearer_auth.py). So a client falls back to scopes_supported. The specification's order is the challenge's scope first, then every scope in scopes_supported, then no scope at all (authorization). That is why scopes_supported should be the smallest set that works, not every scope the server knows: whatever it lists, every host asks every user for.

The authorization server's metadata names the URL the client fetched it from as its issuer, and it states three things the rest of the chapter relies on: PKCE methods ['S256'], support for Client ID Metadata Documents, and iss on authorization responses. The SDK's client makes both matching checks for you. It raises OAuthFlowError when the metadata's issuer differs from the expected one, compared as plain strings (SDK migration guide). Its resource check is laxer than RFC 9728: it accepts metadata whose resource is a same-origin path prefix of the server's URL (mcp/shared/auth_utils.py). A validate_resource_url callback on OAuthClientProvider replaces that check with your own.

Working rule: Give every protected server an AuthSettings with its endpoint's URL as resource_server_url, exactly as clients will type it, and the smallest required_scopes that every request needs. Check the chain with one request that carries no token: a 401, a resource_metadata URL, metadata whose resource is the endpoint, and authorization server metadata whose issuer is the URL you fetched it from. When a value differs by a trailing slash or a port, fix the configuration rather than relaxing the client.

这部分尚未翻译,因此以英文显示。

Identify the client with a metadata document

最近一次修改见于版次 2026.11.14

Find the authorization server from the resource tells the host where to get a token. The authorization server still has to know which client is asking, and a host meets MCP servers it has never seen, so it can't have registered with each one's authorization server in advance. The pinned revision ranks the ways to get a client ID. Pre-registered client information comes first, if there is any. A Client ID Metadata Document comes next, if the authorization server advertises client_id_metadata_document_supported. Dynamic Client Registration follows, and the user is asked only when none of these is available (client registration).

A Client ID Metadata Document makes the client ID a URL. The client publishes a JSON document at an https:// URL with a path, and that URL is its client_id. The document must contain at least client_id, equal to the URL exactly, client_name and redirect_uris (client registration). The authorization server fetches the document when the client first appears, checks the ID and the redirect URI against it, and may cache it by its HTTP headers. It must not follow redirects while fetching, and it must not cache an error (metadata document draft -02).

A document can't carry a shared secret, because client_secret is forbidden. A client identified this way is therefore public, and it relies on PKCE, or proves itself with a key pair through private_key_jwt (draft -02, section 4.1). The MCP specification links draft -00 of that document, and we cite draft -02, the later text. A client ID from a document works with any authorization server. A pre-registered or registered client ID, by contrast, is bound to the server that issued it, and the pinned revision forbids reusing it with another (client registration).

Dynamic Client Registration is deprecated at the pinned revision. It stays as a fallback for authorization servers without metadata document support, and its earliest removal is the first revision released on or after 2027-07-28 (deprecated features). Replace dynamic client registration moves a client off it.

The support team's host publishes its document at https://support.fernhill.example/oauth/client.json. Nothing here reaches a network, and fernhill.example never resolves, so the shop's authorization server can't fetch it. Rather than give the host an http:// client ID that a loopback server could fetch, lib.auth_server keeps the document in a mapping from client ID URL to document. That mapping stands in for the fetch, and the server applies to it the checks it would apply to a fetched copy. This is pre-registration of the URL, which the draft allows as associating a client ID URL with its metadata "through other means" (draft -02, section 5). It is a test-only stand-in, and a deployed authorization server fetches the document over HTTPS.

The code prints the document's key values, runs the server's checks on it and on three broken copies, gives the SDK an http:// client ID, and then connects twice, to an authorization server that supports metadata documents and to one that doesn't.

publish-client-metadata.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""The support host's Client ID Metadata Document, the checks an authorization server makes on it, and the SDK's clientsending its URL as the client ID, with and without the authorization server's support. The point rests on the`client_id sent` line and on the fallback's error line, which show what the SDK did in each case."""import asynciofrom mcp.client.auth import OAuthRegistrationErrorfrom lib import auth_server, oauth_client, protected_shopdocument = auth_server.client_document()                      # served at auth_server.CLIENT_IDprint("client_id:", document["client_id"])print("redirect_uris:", ", ".join(document["redirect_uris"]))print("token_endpoint_auth_method:", document["token_endpoint_auth_method"])for label, url, candidate in [        ("as published", auth_server.CLIENT_ID, document),        ("with a secret", auth_server.CLIENT_ID, auth_server.client_document(client_secret="not-a-secret")),        ("another client_id", auth_server.CLIENT_ID, auth_server.client_document(client_id="https://partner.example/")),        ("on http", "http://support.fernhill.example/oauth/client.json", document)]:    print(f"document {label}:", auth_server.document_problem(url, candidate) or "accepted")try:    oauth_client.provider("http://127.0.0.1/mcp", browser=oauth_client.ScriptedBrowser(),                          client_metadata_url="http://localhost:4280/client.json")   # the SDK checks the scheme when it's builtexcept ValueError:    print("SDK given an http client ID: ValueError")async def connect(**server_options) -> None:    with auth_server.serve(**server_options) as issuer, protected_shop.serve(issuer.url) as url:        browser = oauth_client.ScriptedBrowser()        try:            async with oauth_client.connect(url, browser=browser) as client:                await client.list_tools()            print("client_id sent:", browser.requests[0]["client_id"])        except* OAuthRegistrationError as group:                 # the SDK fell back to registration            print("without metadata document support:", group.exceptions[0])asyncio.run(connect())                                  # the shop's server advertises metadata document supportasyncio.run(connect(advertise_cimd=False))              # a server that doesn't, so the SDK registers instead
输出python publish-client-metadata.py
client_id: https://support.fernhill.example/oauth/client.json
redirect_uris: http://localhost:4280/callback
token_endpoint_auth_method: none
document as published: accepted
document with a secret: document carries a shared secret
document another client_id: document client_id differs from its URL
document on http: client_id must be an https URL with a path
SDK given an http client ID: ValueError
client_id sent: https://support.fernhill.example/oauth/client.json
without metadata document support: Registration failed: 404 Not Found

The document names https://support.fernhill.example/oauth/client.json as its own ID, and its redirect URI is http://localhost:4280/callback. Its token endpoint authentication method is none, so the host holds no secret. The authorization server accepts the document as published.

A copy with a secret fails with "document carries a shared secret", and the other two broken copies fail for the reasons printed beside them: one whose client_id names another site, and one whose client ID is on http. The SDK makes the same https check on its side. Given an http:// client ID, OAuthClientProvider raises ValueError as soon as it is built (mcp/client/auth/utils.py).

The SDK's client uses the document's URL as its client ID, and it falls back quietly when the server doesn't support that. Against the shop's authorization server it sent https://support.fernhill.example/oauth/client.json as the client ID, and made no registration request. Against a server that doesn't advertise support, it fell back to Dynamic Client Registration without a word, and the flow ended with "Registration failed: 404 Not Found", because the shop's authorization server has no registration endpoint. The SDK's documentation calls this fallback silent (OAuth clients). For the host, an authorization server without metadata document support shows up as a registration error, not as a missing feature.

Working rule: Give every host one Client ID Metadata Document at a stable https:// URL, with only the redirect URIs it uses and no secret, and pass that URL to the SDK as client_metadata_url. Use pre-registered credentials where an authorization server has issued them, since they rank first, and keep Dynamic Client Registration only for authorization servers that support nothing else. In tests on loopback, keep the client ID an https:// URL and associate it with a local copy of the document in the test authorization server, rather than giving the client an http:// ID that no production server accepts.

用 PKCE 获取令牌

最近一次修改见于版次 2026.11.11

主机有了从用元数据文档标识客户端中得到的客户端 ID,就可以请求令牌。MCP 使用授权码许可(authorization code grant)。主机把用户的浏览器引导到授权服务器的授权端点,用户登录并同意授权,浏览器带着一个授权码返回主机的重定向 URI。随后,主机在令牌端点用该授权码换取令牌。这一交换过程的安全性,主要由其中三个参数承担。

PKCE 把授权码绑定到发起请求的客户端。客户端生成一个随机的 code_verifier,把它的 SHA-256 哈希值作为 code_challenge 连同 code_challenge_method=S256 一起发送,只在令牌请求中才透露验证器,因此截获授权码的人拿不到它。MCP 客户端必须使用带 S256 的 PKCE;如果授权服务器的元数据中没有 code_challenge_methods_supported,客户端必须拒绝继续(安全注意事项)。OAuth 2.1 自 draft-16 起明确禁止 plain 方法,即质询值就是验证值本身(OAuth 2.1 draft-16,第 7.5.2 节)。MCP 规范引用的是 draft-13,该版本仍允许这种方法(OAuth 2.1 draft-13)。

resource 参数(RFC 8707)通过服务器的规范 URI 指明令牌所针对的服务器。无论授权服务器是否支持该参数,MCP 客户端都必须在授权请求和令牌请求中发送它(授权)。而 state 由客户端在浏览器返回时检查,用来把响应与请求对应起来。

SDK 的客户端为主机运行整个流程,本示例则从授权服务器一侧观察这一流程。lib.oauth_client.connect 给客户端提供一个 OAuthClientProvider,其中带有主机元数据文档的 URL,并用一个脚本化的浏览器代替真人。该浏览器打开授权 URL,跟随重定向,并在遇到第一个指向重定向 URI 的重定向时停止。用户在授权服务器上的同意操作同样由脚本完成:已登录的用户会授予所请求的作用域中其角色允许的全部作用域。示例调用 get_order_status,读取授权服务器记录的日志,然后向授权服务器发送三个 SDK 绝不会发出的请求。

token-with-pkce.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""The SDK's client gets a token for the shop's server with the authorization code grant, PKCE S256 and the resourceparameter, then the authorization server refuses a code sent twice, a wrong verifier and the plain method. The pointrests on the status line, the refusals at the end, and the asserts that check the challenge, the resource and the token."""import asyncioimport osimport httpx2from lib import auth_server, loopback, oauth_client, protected_shop, shop_apiasync def main() -> None:    with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))                  # the server runs in this process        with protected_shop.serve(issuer.url) as url:            browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()            async with oauth_client.connect(url, browser=browser, storage=storage) as client:                result = await client.call_tool("get_order_status", {"order_id": "O-1873"})            print("O-1873 status:", result.structured_content["status"])            asked, exchanged = issuer.events                              # /authorize, then /token            print("authorization request:", ", ".join(key for key in asked if key != "endpoint"))            print("code_challenge_method:", asked["code_challenge_method"])            # the challenge is the hash of the verifier that the token request revealed            assert oauth_client.s256(exchanged["code_verifier"]) == asked["code_challenge"]            assert asked["resource"] == exchanged["resource"] == url                  # the server's URL, in both requests            claims = auth_server.claims(storage.tokens.access_token)            for claim, expected in [("aud", url), ("iss", issuer.url)]:            # the server; the issuer                assert claims[claim] == expected, claim            print("token sub:", claims["sub"])            print("token scope:", claims["scope"])            print("refresh token:", storage.tokens.refresh_token)            again = httpx2.post(issuer.url + "/token", data=exchanged)      # the same code a second time            print("code sent twice:", again.status_code, again.json()["error"])            # the challenge is the hash of a verifier this example knows, so the guessed one is the only thing wrong            code = oauth_client.authorize_by_hand(issuer.url, url, challenge=oauth_client.s256("the-real-verifier"))            stolen = {**exchanged, "code": code["code"], "code_verifier": "a-guessed-verifier"}            print("wrong verifier:", httpx2.post(issuer.url + "/token", data=stolen).json()["error"])            # method="plain" sends the verifier itself as the challenge, which OAuth 2.1 forbids            plain = oauth_client.authorize_by_hand(issuer.url, url, challenge="the-real-verifier", method="plain")            print("plain method:", plain["error"], "/", plain["error_description"])asyncio.run(main())
输出python token-with-pkce.py
O-1873 status: delivered
authorization request: response_type, client_id, redirect_uri, state, code_challenge, code_challenge_method, resource, scope
code_challenge_method: S256
token sub: staff-0007
token scope: orders:read stock:read
refresh token: None
code sent twice: 400 invalid_grant
wrong verifier: invalid_grant
plain method: invalid_request / PKCE with S256 is required

调用成功,订单 O-1873 的状态为 delivered。授权请求带有 response_type, client_id, redirect_uri, state, code_challenge, code_challenge_method, resource, scope,方法为 S256,其质询值是令牌请求所透露的验证值的哈希。两个请求指明的是同一个资源,即该端点的 URL。访问令牌是一个 JWT,其 aud 为服务器的 URL,其 iss 为授权服务器。它的作用域是 orders:read stock:read,即服务器的 scopes_supported,因为那个 401 响应没有指明作用域。

令牌的 sub 为 staff-0007,指的是主机所代表的客服人员,而不是某位客户,服务器可通过 SDK 的 get_access_token().subject 读取它。因此,客服人员的令牌本身不能取代 SHOP_CUSTOMER_ID;在为用户补全参数的订单补全示例中,该值是通过 stdio 从环境变量读取的。对于客服主机,客户应来自客服人员正在处理的工单记录,由服务器查询并核对,绝不能来自工具参数。只有在客户自己登录主机的情形下,sub 才是客户本人,这种情形将在避免服务器沦为混淆代理中讨论。这里没有刷新令牌(None):商店的授权服务器不签发刷新令牌,而且规范告诫客户端不要假定存在刷新令牌(授权)。

SDK 绝不会发送的这三个请求,说明了 PKCE 和一次性授权码能够阻止什么。同一个授权码第二次发送时得到 400 invalid_grant,因为授权码只能使用一次。用新的授权码配上猜测的验证值,得到 invalid_grant,所以仅凭被盗的授权码一文不值。带有 plain 的请求得到“invalid_request / PKCE with S256 is required”,因为商店的授权服务器只接受 S256。

有一项检查要由主机来做。SDK 的客户端总是发送 S256,却从不读取 code_challenge_methods_supported,所以即使授权服务器的元数据中缺少该字段,它也会继续进行(mcp/client/auth/oauth2.py)。必须符合规范的主机,应在连接之前自行获取每个授权服务器的元数据,并拒绝任何未列出 S256 的服务器。

工作准则: 让 SDK 的 OAuthClientProvider 运行授权码流程,并从授权服务器一侧检查一次它发送的内容:S256、state,以及在两个请求中都等于服务器 URL 的 resource。补上 SDK 跳过的那项检查,拒绝元数据中未列出 S256 的授权服务器。在自己运行的授权服务器上,只接受 S256,使授权码一次有效且有效期短,并把每个授权码绑定到其客户端、重定向 URI 和资源。

这部分尚未翻译,因此以英文显示。

Bind each token to one server

最近一次修改见于版次 2026.11.11

The token from Get a token with PKCE names the shop's server in aud, because the host sent resource. That protects no one unless the server checks it. An access token is a bearer credential, so whoever holds it can present it. Suppose the support host also connects to a partner's MCP server that trusts the same authorization server. The partner's server receives the tokens the host gets for it. If the shop's server accepted them, the partner's operator could replay them at the shop. RFC 8707 says the authorization server SHOULD restrict each token's audience to the requested resource, so that a token "legitimately presented to a resource cannot then be taken by that resource and presented elsewhere" (RFC 8707). The other half belongs to the server: MCP servers MUST validate that a token was issued for them as its audience, and MUST NOT accept or pass on any other token (authorization).

In the Python SDK at mcp 2.3.0, the server's half is off by default. AuthSettings.validate_token_resource decides whether the server refuses a token whose AccessToken.resource isn't resource_server_url. Left unset, it warns with MCPDeprecationWarning and behaves as False, and version 3.0 makes True the default (mcp/server/auth/settings.py). The SDK compares the two as URLs. The case of the scheme and host, a default port or a trailing slash makes no difference (mcp/server/auth/middleware/bearer_auth.py), and the comparison uses whatever your token verifier puts in AccessToken.resource. The other way is a verifier that checks aud itself.

Two tokens show which check does the work. The example signs both with the shop's authorization server's key, one for the shop's server and one for the partner's, https://partner.example/mcp, and presents each to the shop's server in three configurations: the SDK's default, validate_token_resource=True, and a verifier that passes the shop's URL to the JWT library as the expected audience.

wrong-audience-rejected.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""A token issued for another server, presented to the shop's server: the SDK's default accepts it, and it's refused oncethe server checks the audience, either through AuthSettings or in the token verifier. The point rests on the partner'stoken's status line in each configuration, and on the warning line that the default alone raises."""import warningsfrom mcp.server.auth.settings import AuthSettingsfrom lib import auth_server, http_mcp, shop_toolsPARTNER = "https://partner.example/mcp"                  # another MCP server, with the same authorization serverSCOPES = ["orders:read", "stock:read"]def shop(issuer: str, validate_token_resource: bool | None, verifier_checks_aud: bool):    def build(base_url: str):        resource = base_url + "/mcp"        # the verifier checks aud only when it's given an audience; None checks nothing        verifier = auth_server.JwtVerifier(issuer, audience=resource if verifier_checks_aud else None)        # None leaves the SDK's default in place, which is off and warns; True refuses other servers' tokens        settings = AuthSettings(issuer_url=issuer, resource_server_url=resource, required_scopes=SCOPES,                                validate_token_resource=validate_token_resource)        return shop_tools.create_server(auth=settings, token_verifier=verifier).streamable_http_app()    return buildwith auth_server.serve() as issuer:    for label, validate, in_verifier in [("SDK default", None, False), ("validate_token_resource=True", True, False),                                         ("verifier checks aud", False, True)]:        # record every warning, and show them all, so each configuration reports only what it raised        with warnings.catch_warnings(record=True) as caught:            warnings.simplefilter("always")            with auth_server.serve_built(shop(issuer.url, validate, in_verifier)) as base_url:                url = base_url + "/mcp"                own = auth_server.mint(issuer.url, url, SCOPES)                foreign = auth_server.mint(issuer.url, PARTNER, SCOPES)     # signed by the same authorization server                for name, token in [("own token", own), ("partner's token", foreign)]:                    response = http_mcp.post(url, "tools/list", headers={"Authorization": f"Bearer {token}"})                    print(f"{label}, {name}:", response.status_code)        print(f"{label}, warnings:", ", ".join(sorted({w.category.__name__ for w in caught})) or "none")
输出python wrong-audience-rejected.py
SDK default, own token: 200
SDK default, partner's token: 200
SDK default, warnings: MCPDeprecationWarning
validate_token_resource=True, own token: 200
validate_token_resource=True, partner's token: 401
validate_token_resource=True, warnings: none
verifier checks aud, own token: 200
verifier checks aud, partner's token: 401
verifier checks aud, warnings: none

With the SDK's default, the partner's token got 200, and the server listed its tools for a token issued to someone else. The only sign was a warning at startup, MCPDeprecationWarning. Either check refuses the partner's token. With validate_token_resource=True it got 401, and with the audience check in the verifier it got 401. Both refusals are 401 with invalid_token, the answer the specification gives for a token that isn't valid for the server. The shop's own token was accepted in all three configurations, and neither fix warned.

We recommend validate_token_resource=True, which lib.protected_shop sets. It states the decision beside the server's other authorization settings, and it survives a change of token verifier. Check aud in the verifier as well when the verifier decodes the token anyway, since the second check costs nothing.

Working rule: Set validate_token_resource=True on every protected server, and make the token verifier fill AccessToken.resource from the token's aud. Treat an MCPDeprecationWarning from AuthSettings as a failed deployment, not as noise. Test the check with a token for another resource from the same authorization server, which must get 401. A server that calls another service on a client's behalf gets its own token for that service and never passes the client's token on (Never pass a client's token through).

这部分尚未翻译,因此以英文显示。

Validate the issuer of each response

最近一次修改见于版次 2026.11.11

Binding the audience, as Bind each token to one server does, keeps a token from working at the wrong server. A mix-up attack strikes earlier, at the authorization code. A host that talks to several authorization servers sends each code to whichever server it believes answered. In a mix-up, an attacker's authorization server gets the host to start a flow with it, then sends the user's browser on to an honest authorization server. The honest server's code arrives at the host's redirect URI. The host, still believing it is talking to the attacker, sends the code to the attacker's token endpoint. PKCE alone doesn't stop this, "because the client transmits the code_verifier to the attacker's token endpoint" (security best practices). Nor does resource, which the attacker rewrites in the request it forwards.

The defence is the iss parameter of RFC 9207. The authorization server names itself in its redirect, and the client compares that name with the server it sent the user to. The pinned revision introduced this check (changelog). Before redirecting, the client records the issuer from the authorization server's validated metadata, and it compares iss with that record by exact string comparison, with no normalisation of case, ports or slashes (authorization).

The rules are conditional. Authorization servers SHOULD include iss, and one that does MUST advertise authorization_response_iss_parameter_supported. A client MUST compare an iss that is present, whatever the metadata says, and MUST reject a response without iss only when the server advertised support. Otherwise it proceeds. On a mismatch, the client must not act on or display any error in the response. The specification expects a later revision to make iss a MUST for authorization servers (authorization). Comparing a present iss that wasn't advertised uses the latitude RFC 9207 leaves to local policy, and its default is that clients SHOULD discard such a response (RFC 9207, section 2.4).

The attacker in the shop's case is the partner, and MixUp from lib.auth_server plays it. The partner's MCP server names the attacker's authorization server, which copies the metadata of the shop's authorization server without iss support. Its authorization endpoint forwards the browser to the shop's authorization server, carrying the host's own request rewritten to ask for the shop's server and every scope. The host's client ID is a metadata document URL, which works with any authorization server, so the shop's authorization server sees a request from the real support host.

mix-up-attack-blocked.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""A mix-up attack on the support host, run against a shop server that sends `iss` and one that omits it. The point restson the codes-received lines: the `iss` mismatch leaves the attacker nothing, and without `iss` it gets a token."""import asynciofrom mcp.client.auth import OAuthFlowError, OAuthTokenErrorfrom lib import auth_server, oauth_client, protected_shopasync def attempt(label: str, **shop_options) -> None:    with auth_server.serve(**shop_options) as shop_issuer, protected_shop.serve(shop_issuer.url) as shop_url:        # the attacker's server forwards the browser to the shop's, and the partner's server names the attacker        with auth_server.serve_mix_up(shop_issuer.url, target=shop_url) as attacker, \                protected_shop.serve(attacker.url) as partner_url:            browser = oauth_client.ScriptedBrowser()            try:                async with oauth_client.connect(partner_url, browser=browser) as client:                    await client.list_tools()            except* (OAuthFlowError, OAuthTokenError) as group:                error = group.exceptions[0]                print(f"{label}, host stopped:", type(error).__name__, str(error).split(":")[0])  # the message's first phrase            assert "code" in browser.arrived                                  # the user consented at the shop's server            print(f"{label}, iss in the answer:", "shop's" if browser.arrived.get("iss") == shop_issuer.url else "none")            print(f"{label}, codes the attacker received:", len(attacker.stolen))            for loot in attacker.stolen:                claims = auth_server.claims(loot["access_token"])                assert claims["aud"] == shop_url                              # the token names the shop's server as its audience                print(f"{label}, attacker's token scope:", claims["scope"])asyncio.run(attempt("shop sends iss"))asyncio.run(attempt("shop omits iss", send_iss=False, advertise_iss=False))
输出python mix-up-attack-blocked.py
shop sends iss, host stopped: OAuthFlowError Authorization response iss mismatch
shop sends iss, iss in the answer: shop's
shop sends iss, codes the attacker received: 0
shop omits iss, host stopped: OAuthTokenError Token exchange failed (400)
shop omits iss, iss in the answer: none
shop omits iss, codes the attacker received: 1
shop omits iss, attacker's token scope: orders:read stock:read refunds:write

The attack runs twice, against a shop authorization server that sends iss and against one that doesn't, and each run prints what the host saw and what the attacker got. In both runs the user consented at the shop's authorization server, because the request in front of them came from the real support host. When the shop sends iss, the answer carried the shop's issuer, the SDK stopped with OAuthFlowError Authorization response iss mismatch, and the attacker received 0 codes.

When the shop omits iss, the answer carried none, and the SDK went on, as the specification says it should for a server that never advertised iss. The attacker received 1 code with its verifier, redeemed it at the shop's authorization server, and holds a token for the shop's server with the scope orders:read stock:read refunds:write, refunds included. The host saw only OAuthTokenError Token exchange failed (400).

So the check protects a host only when the honest server sends iss. The security best practices say the check gives no protection against an honest server that omits iss (security best practices). The SDK follows the specification's table exactly (validate_authorization_response_iss in mcp/client/auth/utils.py). Whether the shop's tokens can be stolen this way therefore depends on the shop's authorization server, not on the host. The other defence RFC 9700 describes, a distinct redirect URI for each authorization server, doesn't help this host. RFC 9700 says it "cannot be used in scenarios where clients only register once for the use of many different issuers", and it should be used only when nothing else is available (RFC 9700, section 4.4.2.2). A client identified by a metadata document is that case, with one client_id and one list of redirect URIs for every authorization server, so the honest server accepts whichever listed URI the attacker forwards. What a host can do without the server's help is limit which authorization servers it uses at all. An attacker's server that isn't on the host's allow-list never starts a flow.

Working rule: Send iss from every authorization server you run, and advertise it with authorization_response_iss_parameter_supported: true, so that clients reject an answer without it. In a host, keep the SDK's check, add no normalisation around it, and treat a mismatch as an attack: show the user none of that response's error text. When a host must use an authorization server that doesn't send iss, keep the host to an allow-list of authorization servers, and refuse or warn the user about any server not on it. Don't count on a separate redirect URI per server when the host is identified by a metadata document.

按令牌允许的范围限定工具

最近一次修改见于版次 2026.11.11

在完成将每个令牌绑定到一台服务器和验证每个响应的签发者中的检查之后,商店的服务器已经知道调用者是谁,但仍需决定每个调用者可以做什么。令牌列出了已授予的权限范围(scope)。商店共有三个:orders:read用于查找、读取和报价订单,stock:read用于查询库存,refunds:write用于发起退款,只有客服主管才能授予。

SDK 按端点检查权限范围,而不是按工具检查。AuthSettings.required_scopes适用于每一个请求,而 SDK 自带的 403 响应并未指明任何scope(mcp/server/auth/middleware/bearer_auth.py)。规范要求给出客户端可以据以行动的质询:返回带有WWW-Authenticate: Bearer error="insufficient_scope"的 403,其中包含操作所需的scope以及resource_metadata,并且要在“单个质询中给出当前操作所需的全部权限范围”(授权)。HTTP 中间件可以发送这样的响应。在所固定的修订版本中,每个tools/call都在Mcp-Name标头中写明其工具名,但服务器在将其与请求体比较之前,必须先解码其=?base64?...?=形式(Streamable HTTP)。如果只检查原始标头,经过编码的issue_refund就会被放行。此外,2025-11-25 修订版的客户端(SDK 的服务器仍在同一端点上接受它)根本不会发送Mcp-Name。

因此,lib.tool_scopes.require依据服务器将要执行的内容来做决定,并使用 SDK 所用的凭据。它从已解析请求体的params.name中读取工具名,而Mcp-Name标头按 SDK 的解码方式解码后,必须与该名称一致,否则请求将得到 -32020,即HeaderMismatch。如果请求体不是单个 JSON 对象,或者含有重复的键,就会被拒绝。SDK 使用第一个Authorization标头进行认证(mcp/server/auth/middleware/bearer_auth.py),所以中间件会以 400 invalid_request拒绝带有两个该标头的请求,并通过 SDK 的BearerAuthBackend读取令牌;对于令牌验证未通过的工具调用,则返回 401。

中间件默认拒绝:映射表中没有的工具会被拒绝。不指向任何对象的方法,例如tools/list,只需要端点的权限范围;其他任何方法,例如prompts/get、resources/read或tasks/get,都会得到 403。lib.protected_shop映射了全部五个工具,lib.tool_scopes.hide_unscoped可以隐藏令牌无法调用的工具(保持工具列表精简)。在持有两个读取权限范围的情况下,该示例分别在关闭和开启隐藏时列出工具,然后发送手写的调用。

refund-needs-a-scope.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""The shop's server refuses a refund without `refunds:write` with a 403 challenge, decided on the parsed body rather thanon `Mcp-Name` or the first `Authorization` header, refuses methods no scope maps, and can hide the tools a token can'tcall. The point rests on the 403 lines, and on the refusals a header-only check would have let through: the spellings of`Mcp-Name`, the 2025-11-25 client, and the second header."""import jsonimport osfrom lib import auth_server, http_mcp, loopback, protected_shop, shop_apiREFUND = {"name": "issue_refund", "arguments": {"quote_id": "Q-00000000aa"}}IN_BASE64 = "=?base64?aXNzdWVfcmVmdW5k?="                                   # "issue_refund", as the spec encodes itdef bearer(token: str, **headers: str) -> dict[str, str]:    return {"Authorization": f"Bearer {token}", **headers}with auth_server.serve() as issuer, loopback.serve(shop_api.create_app()) as api_url:    os.environ.update(shop_api.server_env(api_url))                       # the server runs in this process    for hide in (False, True):                                       # hiding off, then on        with protected_shop.serve(issuer.url, hide_tools=hide) as url:  # hide_tools drops the tools this token can't call            token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])            listed = http_mcp.post(url, "tools/list", headers=bearer(token)).json()["result"]            print(f"hide_tools={hide}, tools listed:", ", ".join(tool["name"] for tool in listed["tools"]))    print("tools/list cacheScope:", listed["cacheScope"])                 # the SDK's default, which suits a list that depends on the token    with protected_shop.serve(issuer.url) as url:        token = auth_server.mint(issuer.url, url, ["orders:read", "stock:read"])        status = http_mcp.post(url, "tools/call", {"name": "get_order_status", "arguments": {"order_id": "O-1873"}},                               headers=bearer(token))        print("get_order_status:", status.status_code)        refused = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token))        print("issue_refund:", refused.status_code)        print("challenge:", refused.headers["www-authenticate"].split(", resource_metadata")[0])   # the challenge without its URL        assert "resource_metadata=" in refused.headers["www-authenticate"]        # the header claims a tool the token may call, but the body asks for the refund, which the server must refuse        lying = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": "get_order_status"}))        print("issue_refund named get_order_status in Mcp-Name:", lying.status_code, lying.json()["error"]["code"])        encoded = http_mcp.post(url, "tools/call", REFUND, headers=bearer(token, **{"Mcp-Name": IN_BASE64}))        print("issue_refund with Mcp-Name in base64:", encoded.status_code)        # revision 2025-11-25 sends no Mcp-Name header at all, so the server must check the body for it        print("issue_refund at 2025-11-25:", protected_shop.call_at_2025_11_25(url, token, REFUND).status_code)        # two Authorization headers: the read-only token first, then junk, which the server must refuse outright        twice = protected_shop.call_with_headers(url, REFUND, [("Authorization", f"Bearer {token}"),                                                               ("Authorization", "Bearer x")])        print("issue_refund with two Authorization headers:", twice.status_code, twice.json()["error"])        # prompts/get names a prompt, not a tool, so no scope in the map covers it and the server refuses it        unmapped = http_mcp.post(url, "prompts/get", {"name": "review_refund"}, headers=bearer(token))        print("prompts/get, which no scope maps:", unmapped.status_code)        lead = auth_server.mint(issuer.url, url, ["orders:read", "stock:read", "refunds:write"])        allowed = http_mcp.post(url, "tools/call", REFUND, headers=bearer(lead))        print("issue_refund with a lead token:", allowed.status_code, json.loads(allowed.text)["result"]["isError"])
输出python refund-needs-a-scope.py
hide_tools=False, tools listed: find_orders, get_order_status, quote_refund, issue_refund, check_stock
hide_tools=True, tools listed: find_orders, get_order_status, quote_refund, check_stock
tools/list cacheScope: private
get_order_status: 200
issue_refund: 403
challenge: Bearer error="insufficient_scope", scope="refunds:write"
issue_refund named get_order_status in Mcp-Name: 400 -32020
issue_refund with Mcp-Name in base64: 403
issue_refund at 2025-11-25: 403
issue_refund with two Authorization headers: 400 invalid_request
prompts/get, which no scope maps: 403
issue_refund with a lead token: 200 True

服务器从请求体中的工具获取权限范围。get_order_status得到200,issue_refund得到403,并附带质询Bearer error="insufficient_scope", scope="refunds:write"。该质询指明了refunds:write,并带有一个resource_metadata URL。

关闭隐藏时,令牌看到的是find_orders, get_order_status, quote_refund, issue_refund, check_stock;开启隐藏时,看到的是find_orders, get_order_status, quote_refund, check_stock。无论哪种情况,列表的缓存范围都是private。这是 SDK 的默认值,适合依赖令牌的列表(缓存列表结果)。

一次退款的Mcp-Name声称是get_order_status,得到的是400 -32020。两个仅检查标头就会放行的请求,因权限范围不足而被拒绝。Mcp-Name以 Base64 编码的退款得到403,来自 2025-11-25 客户端的退款得到403。

使用只读令牌并带有一个无用的第二个Authorization标头的退款,得到400 invalid_request。如果检查读取的是最后一个标头,SDK 就会在只读令牌下完成退款。未映射的prompts/get得到403。持有refunds:write时,调用到达了工具,工具返回200 True:先是状态,然后是结果的isError,其值为 true,因为示例中的报价 ID 不存在。

工作准则: 把每个工具映射到它所需的权限范围,并且只使用 SDK 所认证的那个凭据来授权已解析的请求,绝不能只依据某个标头。拒绝带有两个Authorization标头的请求,以及映射表未涵盖的任何方法。将Mcp-Name视为一个提示,解码后必须与请求体一致;对于无法按服务器的方式精确解析的请求体,一律拒绝。对缺失的权限范围,返回 403 insufficient_scope质询,并在其中列出该工具的全部权限范围;同时让required_scopes只包含每个请求都需要的权限范围。

这部分尚未翻译,因此以英文显示。

Ask for more scope when a call needs it

最近一次修改见于版次 2026.11.14

Step-up is the 403 from Scope tools by what the token allows and the client's answer to it: on insufficient_scope, the client authorizes again with the union of the scopes it asked for before and the scopes in the challenge, retries, and limits how many times it tries (authorization). The union rule is in the pinned revision's text, not in revision 2025-11-25's (2025-11-25 authorization). Without it, a client asking for refunds:write alone would lose orders:read, and its next order lookup would restart the cycle. The SDK's client steps up on 403 and unions the scopes (mcp/client/auth/oauth2.py).

A support lead and a staff member without that role each refund order O-1004 through the SDK's client. The refund, €24.98, is within the policy limit, so no confirmation is involved. The scripted consent lets the lead grant all three scopes and the other user only the two read scopes.

step-up-for-refunds.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · pyjwt 2.15.1 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Step-up: the SDK's client meets the refund's 403, authorizes again for the union of its scopes and `refunds:write`, andretries. A user who may not grant `refunds:write` gets a token without it and a failed refund. The point rests on therefund status line for the lead and the refund failure line for the other user, with the scopes each authorization asked for."""import asyncioimport osfrom lib import auth_server, loopback, oauth_client, protected_shop, shop_apiasync def refund(label: str, user_scopes: tuple[str, ...]) -> None:    # user_scopes are the scopes this user may grant at consent; the scripted browser grants no more    with auth_server.serve(user_scopes=user_scopes) as issuer, protected_shop.serve(issuer.url) as url:        browser, storage = oauth_client.ScriptedBrowser(), oauth_client.MemoryStorage()        async with oauth_client.connect(url, browser=browser, storage=storage) as client:            quote = await client.call_tool("quote_refund", {"order_id": "O-1004", "reason": "arrived cracked"})            print(f"{label}, quote amount:", quote.structured_content["amount"])            print(f"{label}, quote within limit:", quote.structured_content["within_limit"])            try:                result = await client.call_tool("issue_refund", {"quote_id": quote.structured_content["quote_id"]})                print(f"{label}, refund status:", result.structured_content["status"])            except Exception as error:                print(f"{label}, refund failed:", type(error).__name__, error)        for number, asked in enumerate(browser.requests, start=1):          # one request per authorization, in order            print(f"{label}, authorization {number} asked for:", asked["scope"])        print(f"{label}, token scope:", auth_server.claims(storage.tokens.access_token)["scope"])async def main() -> None:    with loopback.serve(shop_api.create_app()) as api_url:        os.environ.update(shop_api.server_env(api_url))                    # the server runs in this process        await refund("lead", auth_server.SCOPES)        await refund("non-lead", ("orders:read", "stock:read"))asyncio.run(main())
输出python step-up-for-refunds.py
lead, quote amount: 24.98
lead, quote within limit: True
lead, refund status: requested
lead, authorization 1 asked for: orders:read stock:read
lead, authorization 2 asked for: orders:read stock:read refunds:write
lead, token scope: orders:read stock:read refunds:write
non-lead, quote amount: 24.98
non-lead, quote within limit: True
non-lead, refund failed: MCPError Server returned an error response
non-lead, authorization 1 asked for: orders:read stock:read
non-lead, authorization 2 asked for: orders:read stock:read refunds:write
non-lead, token scope: orders:read stock:read

The lead's first authorization asked for orders:read stock:read, the two read scopes. The refund's 403 started a second, which asked for orders:read stock:read refunds:write, the union, although the challenge named only refunds:write. The retry went through, and the refund's status is requested.

The other user's second authorization asked for the same union. The user could grant only orders:read stock:read, and the retried call failed with MCPError Server returned an error response. The SDK stepped up once and stopped, so there was no loop. But the host got a generic error, not "this needs a lead".

Working rule: Let the SDK step up, and keep its union of scopes. List every tool a caller could gain by step-up, since a hidden tool never gets the 403 that starts it. In the host, compare the scope the token response granted with the scope the challenge asked for. When they differ, treat it as a decision, not a fault: tell the user which scope the call needs, and pass the ticket to someone who holds it. Never let an authorization server grant by step-up what a user's role doesn't allow. The client only asks, and the authorization server decides.

这部分尚未翻译,因此以英文显示。

What goes wrong in production

最近一次修改见于版次 2026.11.11

The shop's server, its authorization server and its host all work on loopback. In production they meet other people's authorization servers, gateways and clients, and each of the failures that follow leaves a trace you can look for.

An authorization server that doesn't send iss. It is a SHOULD at the pinned revision, so some authorization servers leave it out, and the SDK then proceeds without any defence against mix-up (Validate the issuer of each response). The sign is metadata without authorization_response_iss_parameter_supported. Check the metadata of each authorization server your host meets, and keep the host to an allow-list of authorization servers while any of them leaves iss out.

The silent fallback to registration. When an authorization server doesn't advertise Client ID Metadata Document support, the SDK registers dynamically without saying so (OAuth clients). Look for registration errors, or a growing list of registered clients at the authorization server. Log which kind of client ID each connection used.

The audience check is off. A server without validate_token_resource accepts tokens issued for other servers, and the only sign is an MCPDeprecationWarning at startup (Bind each token to one server). Make warnings from AuthSettings fail the deployment.

An issuer with a trailing slash. The issuer comparison is by exact string, so https://auth.fernhill.example and https://auth.fernhill.example/ are different issuers, and the SDK raises "Authorization server metadata issuer mismatch". The SDK's metadata models keep a URL without a path as it was sent, but an AnyHttpUrl object built in Python still gains the slash. Pass URLs to the SDK as strings (SDK migration guide). You'll see OAuthFlowError on the first connection to a server, from every host.

No PKCE check in the host. The SDK's client never reads code_challenge_methods_supported (Get a token with PKCE). Nothing fails, so the only sign is an audit: fetch each authorization server's metadata and look for S256.

A localhost redirect taken over. A metadata document proves which domain a client belongs to, not which program listens on a localhost redirect URI, and any local program can bind the port first. The specification says that metadata documents "cannot prevent localhost URL impersonation by themselves", and it asks authorization servers to show the redirect's host name to the user and to warn about localhost-only redirect URIs (security considerations). The giveaway is a consent screen that names the real host for a request no one at that machine made.

An authorization server used to probe the network. A server that fetches any client ID URL can be pointed at internal addresses. The draft says authorization servers MUST NOT fetch from special-use addresses, with a loopback exception only for development servers that themselves run on loopback (metadata document draft -02, section 8.6). Watch for metadata fetches to private addresses in the authorization server's logs.

Consent every few minutes. The shop's authorization server issues no refresh token, so the host runs the whole flow again whenever a token expires, and the user consents again. If you issue refresh tokens to hosts, which are public clients, the authorization server MUST rotate them, and MCP servers SHOULD NOT list offline_access in their challenges or scopes_supported (authorization). It shows up as authorization requests from one host at the token lifetime's interval.

Step-up that can never succeed. A server whose 403 names a scope the authorization server doesn't know, or one the user's role can't grant, sends every such call through a second authorization that fails. Pairs of authorization requests for one tool call, followed by a generic error in the host, are the tell (Ask for more scope when a call needs it).

Working rule: Run three probes against the deployment before the shop's server takes traffic. A request without a token gets 401 with a resource_metadata URL. A token for another resource gets 401. A refund with a read-only token gets 403 with scope="refunds:write", and the same refund with a second Authorization header gets 400. Then check the metadata of every authorization server your hosts use for S256, iss support and metadata document support, and watch the 401s, 403s and authorization requests per host.

这部分尚未翻译,因此以英文显示。

Decisions this chapter made

最近一次修改见于版次 2026.11.11
  • The shop's server is an OAuth resource server over Streamable HTTP, configured with the SDK's AuthSettings: its endpoint's URL as resource_server_url, orders:read and stock:read as required_scopes, and validate_token_resource=True.
  • The examples use a teaching authorization server, lib.auth_server, not the SDK's built-in one: S256 only, resource required, iss sent and advertised, single-use codes, JWT access tokens with aud and scope, and no refresh tokens. It signs no one in, and its key derives from the book's public seed, so it must never be deployed. A deployment uses an established authorization server that offers S256 only, honours resource, sends and advertises iss, and supports Client ID Metadata Documents.
  • The support host is identified by a Client ID Metadata Document at an https:// URL on support.fernhill.example. In the examples the authorization server holds a local copy of the document in place of fetching it, and Dynamic Client Registration isn't offered.
  • Hosts use the SDK's OAuthClientProvider with client_metadata_url, and add the PKCE support check the SDK leaves out.
  • Tokens are checked for audience by AuthSettings, and the token verifier reports aud as AccessToken.resource.
  • Scopes are per tool: orders:read for finding, reading and quoting orders, stock:read for stock, and refunds:write, which only support leads can grant, for refunds. An HTTP middleware decides on the parsed JSON-RPC body, with Mcp-Name only as a hint that must match it, and with the one token the SDK authenticates, refusing a second Authorization header. It answers a missing scope with a 403 challenge, and refuses tools and named methods that it doesn't map.
  • refunds:write arrives by step-up, never by default. It isn't in scopes_supported, and the SDK's client asks for the union of scopes when a refund needs it.
  • Every tool stays in tools/list, so that step-up can start. Hiding tools by scope is available in lib.tool_scopes and unused.
  • Who the host acts for comes from the verified token's sub, through get_access_token(), never from a tool argument: for the support host, a member of staff. The customer a ticket concerns comes from the ticket record, which the server looks up and checks, not from the token or an argument. Where customers sign in themselves, see Keep the server from acting as a confused deputy.

本章,在本版次中

版次 2026.11.14示例于 2026年11月19日 通过本章 7个示例 个示例中有 7 个通过

译自英文版图书,版次 2026.11.14。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 8 章,共 12 章: 使用 OAuth 授权客户端

  1. Find the authorization server from the resource
  2. Identify the client with a metadata document
  3. 用 PKCE 获取令牌
  4. Bind each token to one server
  5. Validate the issuer of each response
  6. 按令牌允许的范围限定工具
  7. Ask for more scope when a call needs it
  8. What goes wrong in production
  9. Decisions this chapter made

返回顶部全部章节