MCP服务器授权机制与实现要点
MCP服务器授权为可选能力,涉及用户数据或管理操作时建议启用。MCP服务器作为OAuth资源服务器,需校验令牌受众、提供元数据,并注意令牌透传与代理场景的边界。
模式上下文协议(MCP)的授权可以保障对MCP服务器所暴露的敏感资源和操作的访问. 如果您的MCP服务器处理用户数据或行政行动,授权只允许用户到达其端点. MCP的授权如下: [OAuth 2.1 (英语).](<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13>) 并使用任何符合其要求的授权或身份系统。本指南解释流量,然后显示如何保护一个小服务器。所有要求都在 [授权规格](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization>). ## 您何时使用授权 ? 授权是 **选项** 用于 MCP 服务器。当 : - 您的服务器工作于用户特定数据, 如电子邮件、 文件或数据库 - 你需要审计谁做了哪些行动 - 您的服务器允许访问其需要用户同意的 API - 您正在为企业环境建设严格的访问控制 - 您想要对每个用户的用法进行评分限制或跟踪 **本地 MCP 服务器的授权**本指南中的 OAuth 流量用于基于 HTTP 的传输 。 [钢铁运输](<https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio>) 应该从环境中获取证书。它们会在当地运行,这样它们也可以使用嵌入在服务器的库中的证书。 ## 授权流程:一步一步 参加三场派对,你的 **MCP 服务器** 是一个 OAuth 资源服务器。 它在此作用中验证访问符而不发布它们 。 **MCP 客户端** 是 OAuth 客户端代表用户行事。 **授权服务器** 为您的 MCP 服务器认证用户并发布令牌。 它可以是单独的服务, 也可以与 MCP 服务器一起托管 。 1 初始请求 当客户端在没有有效签名的情况下发送请求时,您的服务器会回复 `401 Unauthorized`。该数字 `WWW-Authenticate` 信头可以指: [保护资源元数据( PRM )](<https://datatracker.ietf.org/doc/html/rfc9728>) 文档。它还应列出访问资源所需的范围。 ``` HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer resource_metadata="https://your-server.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools" ``` 客户端应该请求在挑战中命名的范围。 如果挑战没有名称, 它应该请求在 PRM 文档中的全部内容 `scopes_supported`如果这个也不见了,那就省去了 `scope` 参数。 [范围选择战略](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#scope-selection-strategy>)服务器必须包含 `resource_metadata` 指针或服务于PRM文档,在知名URI。它既可以做到两者。当指针缺失时,客户端首先尝试 `/.well-known/oauth-protected-resource` 之后是 MCP 端点的路径。 然后它会尝试同样的 URL 而不使用路径 。 见 [保护资源元数据发现要求](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/authorization-server-discovery#protected-resource-metadata-discovery-requirements>). 2 保护资源元数据发现 客户端获取 PRM 文档,以了解 MCP 服务器信任的哪些授权服务器. `authorization_servers` 必须包含至少一个条目。 ``` { "resource": "https://your-server.com/mcp", "authorization_servers": ["https://auth.your-server.com"], "scopes_supported": ["mcp:tools"] } ``` `resource` 识别您的 MCP 服务器。 请使用客户端连接的 URL 。 [RFC 9728 部分 3.3](<https://datatracker.ietf.org/doc/html/rfc9728#section-3.3>) 说客户不得使用其文档 `resource` 与我不同。 3 授权服务器发现 客户端选择一个授权服务器并获取其元数据。 元数据可以在 [OAuth 2.0 授权服务器元数据](<https://datatracker.ietf.org/doc/html/rfc8414>) 或一个 [OpenID 连接发现](<https://openid.net/specs/openid-connect-discovery-1_0.html>) URL. 客户端必须支持两者并尝试在 [命令定义的规格](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/authorization-server-discovery#authorization-server-metadata-discovery>). ``` { "issuer": "https://auth.your-server.com", "authorization_endpoint": "https://auth.your-server.com/authorize", "token_endpoint": "https://auth.your-server.com/token", "jwks_uri": "https://auth.your-server.com/jwks", "response_types_supported": ["code"], "grant_types_supported": ["authorization_code", "refresh_token"], "token_endpoint_auth_methods_supported": ["none"], "code_challenge_methods_supported": ["S256"], "client_id_metadata_document_supported": true, "authorization_response_iss_parameter_supported": true } ``` 客户端必须检查其中两个值: - `issuer` 必须和用于构建元数据URL的发行者标识符完全相同。如果不是,客户端不得使用文档。 - `code_challenge_methods_supported` 必须在场。 如果不存在, 客户端必须拒绝继续, 因为授权服务器不支持 PKCE 。 4 客户注册 客户端需要客户端 ID , 授权服务器接受。 选项摘要如下 。 [客户注册办法](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/authorization#client-registration-approaches>). 5 用户授权 客户端打开浏览器 `authorization_endpoint`请求中包括: [PKCE](<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-7.5.2>) `code_challenge` 页:1 `resource` 参数 ([RFC 8707](<https://datatracker.ietf.org/doc/html/rfc8707>)),设置为MCP服务器的URL: ``` GET /authorize?response_type=code &client_id=https%3A%2F%2Fapp.example.com%2Foauth%2Fclient-metadata.json &redirect_uri=http%3A%2F%2F127.0.0.1%3A8090%2Fcallback &scope=mcp%3Atools &resource=https%3A%2F%2Fyour-server.com%2Fmcp &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM &code_challenge_method=S256 &state=af0ifjsldkj HTTP/1.1 Host: auth.your-server.com ``` 此示例中的换行符只是为了便于读取。 用户登录和同意后, 授权服务器会以一个 `code` 页:1 `state`。如果支持的话。 [RFC 9207](<https://datatracker.ietf.org/doc/html/rfc9207>),它也会返回 `iss`。在打开浏览器之前,客户端必须记录 `issuer` 在交换代码之前,它必须 [校验 `iss`](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#authorization-response-validation>) 如果授权服务器广告支持 `iss`,客户端必须拒绝一个将它排除在外的响应。同样的检查适用于错误响应。如果错误响应失败,客户端不得对错误采取行动或显示错误。客户端还应当放弃一个其反应。 `state` 缺少或与其发送的值不同。客户端然后发送代码, PKCE 验证器, 和相同的 `resource` 值为 `token_endpoint`。它收到访问令牌,授权服务器也可以选择返回刷新令牌: ``` { "access_token": "eyJhbGciOiJSUzI1NiIs...", "token_type": "Bearer", "expires_in": 3600, "scope": "mcp:tools" } ``` 6 提出认证请求 客户端发送访问符 `Authorization` 标题 **每张** HTTP请求,从未在URL中: ``` POST /mcp HTTP/1.1 Host: your-server.com Authorization: Bearer eyJhbGciOiJSUzI1NiIs... Content-Type: application/json Accept: application/json, text/event-stream MCP-Protocol-Version: 2026-07-28 Mcp-Method: tools/list { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": { "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": { "name": "ExampleClient", "version": "1.0.0" }, "io.modelcontextprotocol/clientCapabilities": {} } } } ``` 在处理请求之前, MCP 服务器将验证该令牌, 并检查该令牌是为该服务器发布的。 无效或过期的令牌会得到一个 `401`。如果该令牌是有效的,但缺少范围,服务器应当以 `403 Forbidden` 备忘 `insufficient_scope` 挑战: ``` HTTP/1.1 403 Forbidden WWW-Authenticate: Bearer error="insufficient_scope", scope="mcp:tools", resource_metadata="https://your-server.com/.well-known/oauth-protected-resource/mcp" ``` 然后客户端应该启动一个 [逐步增加授权流量](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#step-up-authorization-flow>)它要求将挑战的范围与它以前所要求的范围结合起来,并应限制其重复讨论的次数。 ## 客户注册办法 | 方针 | 何时使用 | | --- | --- | | **预先登记** | 客户端已经拥有此授权服务器的证书 | | **客户端 ID 元数据文档** | 客户端和服务器没有前置关系( 最常见的) | 支持两者的客户端应该按此顺序进行尝试。 如果两者都不可用, 它应该请用户输入客户端 ID, 如果有客户端, 则请输入客户端的秘密 。 [客户注册](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration>). 动态客户注册( DCR ) 是 [已贬值](<https://modelcontextprotocol.io/specification/2026-07-28/deprecated>) 作为协议版本 `2026-07-28`应采用新的实施办法 [客户端 ID 元数据文档](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/authorization#client-id-metadata-documents>) (CIMD)取而代之. 现有客户端可以 [返回到 DCR 中](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#dynamic-client-registration>) 在向用户询问客户端 ID 和秘密之前。如果授权服务器不支持 CIMD 并允许客户端在运行时通过它注册,则此程序将适用 `registration_endpoint`. ### 客户端 ID 元数据文档 与一个 [客户端 ID 元数据文档](<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00>) (CIMD),客户端使用HTTPS URL作为它的. `client_id` ,并在那里托管一个 JSON 文档。授权服务器收到授权请求时会获取文档并对其进行验证。 ``` { "client_id": "https://app.example.com/oauth/client-metadata.json", "client_name": "Example MCP Client", "redirect_uris": ["http://127.0.0.1:8090/callback"], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "token_endpoint_auth_method": "none" } ``` URL 必须使用 `https` 并包含路径,例如 `/oauth/client-metadata.json`。该文件必须至少包含 `client_id`, `client_name`,以及 `redirect_uris`,及其分类 `client_id` 必须精确匹配 URL 。 授权服务器广告支持 `"client_id_metadata_document_supported": true`。客户端可以使用相同的客户端 ID 与每个支持 CIMD 的授权服务器。如果您的 MCP 服务器更改授权服务器,则无需再次注册 。 ### 预先登记 客户端 ID 预先设置,如果需要的话,还要同时设置证书,可以建在客户端内,也可以由用户输入。证书属于发布证书的授权服务器。客户端必须保存这些证书。 `issuer` 永远不要用另一个。 [授权服务器绑定](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#authorization-server-binding>). ## 选择授权服务器 使用现有的身份提供者或授权服务器产品。客户端注册发生在客户端和授权服务器之间,所以您的 MCP 服务器不需要注册代码。 在您选择一个前请检查这些点 : - **观众。** 您的 MCP 服务器必须拒绝未为此发布的符号 。 `resource` 客户的值应该成为象征性的受众,即 `aud` A. 索赔中的索赔JWT。有些产品需要设置,或者让你在范围上配置观众。其他产品总是使用自己的标识符。在这种情况下,将受众与标识符进行比较,并保留服务器的标识符。URL作为PRM `resource`。标识符必须只属于这个 MCP 服务器, 所以不要在服务器之间共享一个应用程序注册 。 - **元数据。** 它必须通过 RFC 8414 或 OpenID 连接发现服务元数据。元数据必须包含 `code_challenge_methods_supported`。看看真实的文档,因为有些产品支持PKCE,但将这一值保留在外,然后遵循规格的客户端拒绝连接. - **CIMD.** 它应该支持CIMD公司, `client_id_metadata_document_supported`。在有些产品中,您必须启用此功能,或者列出您接受的客户端域。 - **托肯格式化( Token).** 下面的例子需要签名的 JWT 访问令牌。 否则, 您需要一个反省结束点 。 - **公共客户.** 许多 MCP 客户端没有秘密。授权服务器必须接受它们, 及其 `token_endpoint_auth_methods_supported` 应包含 `none`. - **范围。** 定义范围,例如: `mcp:tools` 并提供给将连接的客户。有些产品在范围名称中添加一个前缀。如果您有,请在示例中使用全名。 `mcp:tools`。如果定义了多个范围,请读作 [范围最小化](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#scope-minimization>)中,并仅列出基本使用所需的范围。 `scopes_supported`. - **托肯终身.** 访问令牌应该是短命的, 因为被窃令牌在到期前有效。 授权服务器必须为公共客户端旋转刷新令牌 。 - **发行者在回应中。** 应该会回来的 `iss` 如果有,它必须做广告 `authorization_response_iss_parameter_supported`. **本地测试**您可以在自己的机器上运行授权服务器。例如, [键盘](<https://www.keycloak.org/securing-apps/mcp-authz-server>) 具有对 CIMD 和资源指标的实验支持。为了实现两者,请从 `--features=cimd,resource-indicators`。然后,您必须为 CIMD 创建客户端政策,并将您的服务器的 URL 添加到其资源指标允许列表中 。 ## 执行实例 下面的例子保护一个拥有一个工具的MCP服务器, `add`。每个服务器运行于 `http://localhost:3000/mcp`,则要求 `mcp:tools` 范围, 并接受与 JWT 签名的 RS256 访问令牌。 在运行一个前, 更改这些值 : - `ISSUER` 准确无误 `issuer` 从您授权服务器的元数据中得出的值。 - `METADATA_URL` 是该元数据中的 URL。如果发行者有路径, 如 `https://auth.example.com/tenant1`, RFC 8414 URL是: is is is is is is `https://auth.example.com/.well-known/oauth-authorization-server/tenant1`,而且 OpenID 连接 URL 通常是 `https://auth.example.com/tenant1/.well-known/openid-configuration`. - `RS256` (`RsaSha256` 在 C# 中) 是签名算法。 如果您的授权服务器使用不同的算法, 请更改它。 在 Python 中, 已发布的密钥必须有一个 `alg` 数值。 - `mcp:tools` 是所需的范围。 - 期望的受众是服务器 URL。 如果您的授权服务器将自己的标识符放入其中, 请更改它 。 `aud`。这是 `audience` 选项在 TypeScript 和 Python 中,以及 `ValidAudience` 在C# 语录中. 在C#的例子中,前两个被称为 `issuer` 财务报告和财务报告 `metadataUrl`。 TypeScript 和 Python 实例在启动时获取元数据, 如果无法到达授权服务器, 它们就会退出 。 - TypeScript - Python 键 - C# 安装 [TypeScript SDK](<https://ts.sdk.modelcontextprotocol.io/v2/>) 软件包,一个 JWT 库,以及 Zod 4 : ``` npm install @modelcontextprotocol/server@^2.3.0 @modelcontextprotocol/express@^2.0.2 \ @modelcontextprotocol/node express jose zod@4 npm install --save-dev tsx @types/express ``` 设定 `"type": "module"` 输入 `package.json`创建 `server.ts`: ``` import { createMcpExpressApp, getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter, requireBearerAuth, } from "@modelcontextprotocol/express"; import { toNodeHandler } from "@modelcontextprotocol/node"; import { createMcpHandler, McpServer, OAuthError, OAuthErrorCode, } from "@modelcontextprotocol/server"; import type { AuthInfo, OAuthMetadata } from "@modelcontextprotocol/server"; import { createRemoteJWKSet, errors, jwtVerify } from "jose"; import * as z from "zod"; // The authorization server's issuer identifier, and where it publishes metadata const ISSUER = "https://auth.example.com"; const METADATA_URL = "https://auth.example.com/.well-known/oauth-authorization-server"; // The URL clients connect to, which is also the audience of their tokens const MCP_SERVER_URL = new URL("http://localhost:3000/mcp"); const metadataResponse = await fetch(METADATA_URL); if (!metadataResponse.ok) { throw new Error(`Metadata request failed: ${metadataResponse.status}`); } const oauthMetadata = (await metadataResponse.json()) as OAuthMetadata; if (oauthMetadata.issuer !== ISSUER) { throw new Error(`Unexpected issuer: ${oauthMetadata.issuer}`); } const jwks = createRemoteJWKSet(new URL(String(oauthMetadata.jwks_uri))); // Errors that mean the keys could not be fetched, not that the token is bad const JWKS_OUTAGE = [ "ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID", "ERR_JOSE_GENERIC", ]; async function verifyAccessToken(token: string): Promise<AuthInfo> { try { const { payload } = await jwtVerify(token, jwks, { algorithms: ["RS256"], issuer: ISSUER, audience: MCP_SERVER_URL.href, requiredClaims: ["exp"], clockTolerance: 30, }); return { token, clientId: String(payload.client_id ?? payload.azp ?? ""), scopes: typeof payload.scope === "string" ? payload.scope.split(" ") : [], expiresAt: payload.exp, // jwtVerify has checked that the token's audience is this server resource: MCP_SERVER_URL, extra: { sub: payload.sub }, }; } catch (error) { // requireBearerAuth answers 401 for an OAuthError with this code, and 500 // for any other exception. if ( error instanceof errors.JOSEError && !JWKS_OUTAGE.includes(error.code) ) { throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid access token"); } console.error("Could not verify the token:", error); throw error; } } function createServer() { const server = new McpServer({ name: "math", version: "1.0.0" }); server.registerTool( "add", { description: "Add two numbers together", inputSchema: z.object({ a: z.number(), b: z.number() }), }, async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }], }), ); return server; } const app = createMcpExpressApp(); app.use( mcpAuthMetadataRouter({ oauthMetadata, resourceServerUrl: MCP_SERVER_URL, scopesSupported: ["mcp:tools"], }), ); const requireAuth = requireBearerAuth({ verifier: { verifyAccessToken }, requiredScopes: ["mcp:tools"], expectedResource: MCP_SERVER_URL, resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(MCP_SERVER_URL), }); const handler = toNodeHandler(createMcpHandler(createServer)); app.all("/mcp", requireAuth, (req, res) => void handler(req, res, req.body)); app.listen(3000, "127.0.0.1", (error) => { if (error) throw error; console.log(`MCP server listening on ${MCP_SERVER_URL}`); }); ``` - `mcpAuthMetadataRouter` 服务于 PRM 文档 : `/.well-known/oauth-protected-resource/mcp`,它也反映了在MCP服务器上寻找它的老客户端的授权服务器元数据. - `requireBearerAuth` 在每次请求中运行您的验证符。它会用一个 `401` 和缺失的镜框,带有 `403` 挑战。 - `jwtVerify` 检查签名、发行人、听众和寿命。 `audience` 选项,因为 `expectedResource` 不看符号。 `expectedResource` 如果核查者报告不同的资源或没有资源,则拒绝一个符号。它要求 `@modelcontextprotocol/express` 2.0.2,早期版本忽略了它. - `createMcpExpressApp` 验证 `Host` 财务报告和财务报告 `Origin` 绑定到本地主机的服务器头 。 运行服务器 : ``` npx tsx server.ts ``` 要求一个单一工具的范围,见 [需要授权](<https://ts.sdk.modelcontextprotocol.io/v2/serving/authorization>) 在TypeScript SDK文档中. 安装 [Python SDK (英语).](<https://py.sdk.modelcontextprotocol.io/>), HTTPX2, 和 PyJWT 与 `crypto` 另外, RS256 需要: ``` pip install "mcp>=2.2" "httpx2>=2.5" "pyjwt[crypto]>=2.14" ``` 创建 `server.py`: ``` import asyncio import httpx2 import jwt from mcp.server import MCPServer from mcp.server.auth.provider import AccessToken, TokenVerifier from mcp.server.auth.settings import AuthSettings # The authorization server's issuer identifier, and where it publishes metadata ISSUER = "https://auth.example.com" METADATA_URL = "https://auth.example.com/.well-known/oauth-authorization-server" # The URL clients connect to, which is also the audience of their tokens MCP_SERVER_URL = "http://localhost:3000/mcp" class JWTTokenVerifier(TokenVerifier): def __init__(self) -> None: metadata = httpx2.get(METADATA_URL).raise_for_status().json() if metadata["issuer"] != ISSUER: raise RuntimeError(f"Unexpected issuer: {metadata['issuer']}") self.jwks_client = jwt.PyJWKClient(metadata["jwks_uri"], timeout=5) async def verify_token(self, token: str) -> AccessToken | None: try: # PyJWKClient blocks while it fetches keys, so keep it off the event loop signing_key = await asyncio.to_thread( self.jwks_client.get_signing_key_from_jwt, token ) claims = jwt.decode( token, signing_key, algorithms=["RS256"], issuer=ISSUER, audience=MCP_SERVER_URL, leeway=30, options={"require": ["exp"]}, ) except jwt.PyJWKClientConnectionError: # An unreachable JWKS endpoint is an outage, not an invalid token raise except jwt.PyJWTError: return None scope = claims.get("scope") return AccessToken( token=token, client_id=claims.get("client_id") or claims.get("azp") or "", scopes=scope.split() if isinstance(scope, str) else [], expires_at=int(claims["exp"]), # jwt.decode has checked that the token's audience is this server resource=MCP_SERVER_URL, subject=claims.get("sub"), claims=claims, ) mcp = MCPServer( "Math", token_verifier=JWTTokenVerifier(), # model_validate keeps ISSUER as it is. AnyHttpUrl(ISSUER) would add a trailing # slash, and the issuer is compared character by character. auth=AuthSettings.model_validate( { "issuer_url": ISSUER, "resource_server_url": MCP_SERVER_URL, "required_scopes": ["mcp:tools"], "validate_token_resource": True, } ), ) @mcp.tool() def add(a: float, b: float) -> float: """Add two numbers together.""" return a + b if __name__ == "__main__": mcp.run(transport="streamable-http", port=3000) ``` - SDK 服务于 PRM 文件 : `/.well-known/oauth-protected-resource/mcp` 并把它从 `AuthSettings`. - 返回时 `None` 从 `verify_token` 生成一个 `401` 挑战 。 `required_scopes` 获得一个 `403` 挑战。 - `jwt.decode` 检查签名、发行人、听众和寿命。 `audience` 参数,因为 `validate_token_resource` 它使 SDK 拒绝一个符号,如果 `AccessToken.resource` 并非“ `resource_server_url`。它需要2.2版本,而先前的版本忽略它。 - SDK没有表示: `scope` A. 克服挑战 `401`,客户端在 `scopes_supported` 换成A后 `403`,一些客户只要求它们已经拥有的范围,所以升级授权可能不会得到缺失的范围. 运行服务器 : ``` python server.py ``` 详情见 [授权](<https://py.sdk.modelcontextprotocol.io/run/authorization/>) 在Python SDK文档中。 此示例使用 [C# SDK](<https://csharp.sdk.modelcontextprotocol.io/>) 和 ASP.NET Core 的 JWT 无记名认证在.NET 10 上。创建 `ProtectedMcpServer.csproj`: ``` <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.14" /> <PackageReference Include="ModelContextProtocol.AspNetCore" Version="2.4.0" /> </ItemGroup> </Project> ``` 创建 `Program.cs`: ``` using System.ComponentModel; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using ModelContextProtocol.Server; // The authorization server's issuer identifier, and where it publishes metadata var issuer = "https://auth.example.com"; var metadataUrl = "https://auth.example.com/.well-known/oauth-authorization-server"; // The URL clients connect to, which is also the audience of their tokens var mcpServerUrl = "http://localhost:3000/mcp"; var serverOrigin = new Uri(mcpServerUrl).GetLeftPart(UriPartial.Authority); var mcpPath = new Uri(mcpServerUrl).AbsolutePath.TrimEnd('/'); var resourceMetadataUrl = $"{serverOrigin}/.well-known/oauth-protected-resource{mcpPath}"; // Browser origins and host names that the server doesn't reject string[] allowedOrigins = [serverOrigin]; var allowedHosts = "localhost;127.0.0.1;[::1]"; var builder = WebApplication.CreateBuilder(args); builder.Configuration["AllowedHosts"] = allowedHosts; builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.MetadataAddress = metadataUrl; options.BackchannelTimeout = TimeSpan.FromSeconds(5); options.RefreshInterval = TimeSpan.FromSeconds(30); options.MapInboundClaims = false; options.TokenValidationParameters = new TokenValidationParameters { // ValidIssuer alone would also accept the issuer named in the metadata IssuerValidatorUsingConfiguration = (tokenIssuer, _, _, configuration) => tokenIssuer == issuer && configuration?.Issuer == issuer ? tokenIssuer : throw new SecurityTokenInvalidIssuerException("Unexpected issuer"), ValidAudience = mcpServerUrl, IgnoreTrailingSlashWhenValidatingAudience = false, ClockSkew = TimeSpan.FromSeconds(30), NameClaimType = "sub", ValidAlgorithms = [SecurityAlgorithms.RsaSha256], }; options.Events = new JwtBearerEvents { // Point clients to the PRM document and name the scope they need OnChallenge = context => { context.HandleResponse(); var error = context.AuthenticateFailure is null ? "" : "error=\"invalid_token\", "; context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.Headers.WWWAuthenticate = $"Bearer {error}scope=\"mcp:tools\", resource_metadata=\"{resourceMetadataUrl}\""; return Task.CompletedTask; }, // If the signing keys were never downloaded, this throws and the client gets a 500 OnAuthenticationFailed = context => context.Options.ConfigurationManager! .GetConfigurationAsync(context.HttpContext.RequestAborted), // Tell clients which scope they need when a valid token lacks it OnForbidden = context => { context.Response.Headers.WWWAuthenticate = $"Bearer error=\"insufficient_scope\", scope=\"mcp:tools\", resource_metadata=\"{resourceMetadataUrl}\""; return Task.CompletedTask; }, }; }) .AddMcp(options => { options.ResourceMetadata = new() { Resource = mcpServerUrl, AuthorizationServers = { issuer }, ScopesSupported = ["mcp:tools"], }; }); builder.Services.AddAuthorizationBuilder() .AddPolicy("mcp:tools", policy => policy .RequireAuthenticatedUser() .RequireAssertion(context => context.User.FindAll("scope") .SelectMany(claim => claim.Value.Split(' ')) .Contains("mcp:tools"))); builder.Services.AddMcpServer() .WithHttpTransport() .WithTools<MathTools>(); var app = builder.Build(); // Reject browser requests from other origins, which protects against DNS rebinding app.Use(async (context, next) => { var origin = context.Request.Headers.Origin.ToString(); if (origin.Length > 0 && context.Request.Path.StartsWithSegments(mcpPath) && !allowedOrigins.Contains(origin)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; return; } await next(); }); app.UseAuthentication(); app.UseAuthorization(); app.MapMcp(mcpPath).RequireAuthorization("mcp:tools"); app.Run("http://localhost:3000"); [McpServerToolType] public sealed class MathTools { [McpServerTool, Description("Add two numbers together.")] public static double Add(double a, double b) => a + b; } ``` - `AddMcp` 服务于 PRM 文档 : `/.well-known/oauth-protected-resource/mcp`. - `AddJwtBearer` 下载签名密钥并验证签名、 发行者、 受众和寿命。 默认在签名到期后接受5分钟的签名, 所以示例集 `ClockSkew`。示例集 `MetadataAddress` 因为 `Authority` 选项只查找 OpenID 连接发现元数据。 - 那个... `mcp:tools` 政策执行范围。 `RequireAuthorization()` 自动接受任何有效的标志。 - `OnChallenge` 财务报告和财务报告 `OnForbidden` 写入 `401` 财务报告和财务报告 `403` SDK公司本身的 `401` 挑战没有 `scope`,并在代理人背后 `resource_metadata` URL可能是错的,它发送不 `403` 挑战。 - JWT 无记名认证只下载到 HTTPS 上的元数据。 与其它 URL 一样, 请求失败 。 `500`。如果您的本地授权服务器使用纯 HTTP ,则设置 `options.RequireHttpsMetadata = false` 输入 `AddJwtBearer`. 只在发展过程中这样做。 - `OnAuthenticationFailed` 让服务器回答 `500` 如果它从未下载签名密钥。没有它, ASP. NET Core 答案 `401`. - ASP.NET Core每次12小时或看到未知密钥时都会再次下载签名密钥。它回答 `401` 在下载完成之前,未知的密钥。默认情况下,它最多每5分钟做一次,所以可以拒绝新密钥持续那么长的时间。示例集 `RefreshInterval` 以缩短这个。 - 那个... [运输规格](<https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http>) 需要服务器验证 `Origin` 标题 。 SDK 不这样做, 所以示例在中间软件中做 。 运行服务器 : ``` dotnet run ``` 每工具授权 `[Authorize]`,见 [身份和角色宣传](<https://csharp.sdk.modelcontextprotocol.io/concepts/identity/identity.html>) 在 C# SDK 文档中。失败 `[Authorize]` 检查工具返回 JSON - RPC 错误和否 `403` 因此客户无法从中启动升级授权。 ### 不透明托肯斯 如果您的授权服务器签发了不透明的令牌, 请使用它 。 [符号反省](<https://datatracker.ietf.org/doc/html/rfc7662>) 结束点而不是验证一个 JWT 。 它的 URL 是 `introspection_endpoint` 。端点需要授权,所以您的 MCP 服务器需要自己在授权服务器上的证书。 如果您使用 HTTP Basic 认证, 请先将客户端 ID 编码为格式并保密。 证书必须被允许为此服务器内置令牌 。 如果不是, 对有效令牌的响应已经存在 。 `active` 设置为 `false`。如果 `active` 为: `false`,拒绝该标志。如果它是 `true`检查 `aud` 在向 SDK 报告资源之前, 包含预期的受众。 请检查 `scope` 财务报告和财务报告 `exp` 。这些值在 RFC 中是可选的, 请确保您的授权服务器返回, 并拒绝一个其符号 。 `aud` 如果无法到达终点或返回一个错误状态,甚至一个 `401`, 将它视为退出。如果缓存符号或结果, 请在符号过期前加密符号并删除每个条目。 请将服务器的证书保存在密件管理器中。 在 TypeScript 和 Python 中, 在验证器中拨打。 在 C# 中, 替换 `AddJwtBearer` 带有一个支持反演的认证处理器. ### 部署在本地主机之外 将服务器 URL 更改为精确 `https` 连接客户端的 URL。 它被用作 PRM `resource` 和预期的观众。如果它的道路不是 `/mcp`,也改变路线。 `app.all` 路径和 TypeScript `streamable_http_path` 理由 `mcp.run` 在 Python 中。 C# 例取自 URL 。在 TypeScript 中, `new URL()` 在无路径的URL和符号上加一条线索斜线 `aud` 然后必须包含。客户端必须在 HTTPS 上到达您的服务器。这些示例服务于纯 HTTP , 因此将它们放在一个反向代理或负载平衡器后面, 终止 TLS 并保存原始 `Host` 标题。 如果它运行在同一台机器上, 请继续收听本地主机, 只更改接受的主机和来源 。 示例只听本地主机, 并拒绝其它任何请求 。 `Host` 标题。 配置您接受的主机和浏览器源 : - **TypeScript**: 传球 `host`, `allowedHosts`,以及 `allowedOrigins` 改为: `createMcpExpressApp`,并更改地址为 `app.listen`。两个列表都会在没有方案或端口的情况下使用主机名称。如果没有浏览器客户端连接,请通过一个空的 `allowedOrigins` 列表, 因为 SDK 不检查 `Origin` 没有它。 `NODE_ENV=production` 让快递不会向客户发送堆栈痕迹。 - **Python 键**: 传球 `host` 备注a `TransportSecuritySettings` 对象为 `transport_security` 改为: `mcp.run`。从中导入类。 `mcp.server.transport_security`,并设定其 `allowed_hosts` 财务报告和财务报告 `allowed_origins`。如果您更改, SDK 将检查两个标题 `host` 别管这个了,一个主机必须匹配 `Host` 精确的页眉, 包括有端口的端口, 并且源代码必须包含其方案。 结束一个条目 `:*` 以接受任何端口。 - **C#**: 更改给定的 URL `app.Run` 地址可以收听,例如: `http://0.0.0.0:3000`。变化 `allowedOrigins`,其条目包括该计划,以及 `allowedHosts`,其条目没有计划或端口。 接受源代码不能允许 CORS 。 在浏览器中运行的客户端也需要 CORS 中间软件,在认证前回答飞行前请求并曝光 `WWW-Authenticate` 标题。 此协议修改没有会话, 所以忽略 `Mcp-Session-Id` 如果您的服务器只支持此修改, 则页眉 。 如果它也接受旧客户端, 请永远不要使用会话 ID 来证明呼叫者是谁 。 见 [会话劫持](<https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices#session-hijacking>) 在2025 - 11 - 25文档中. ## 测试服务器 第一次检查发现。 这些请求不需要符号 : ``` curl -i -X POST http://localhost:3000/mcp curl http://localhost:3000/.well-known/oauth-protected-resource/mcp ``` 第一个命令应打印 a `401` 带一个 `WWW-Authenticate` 页眉。 第二页应打印 PRM 文档, 包含您的服务器的 URL 和您的发行者。 同时打开您的 `METADATA_URL` 并检查是否包含 `code_challenge_methods_supported`。一些客户没有它而工作,另一些则拒绝连接。然后运行全流与 [MCP 检查员](<https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/authorization>),这需要节点.js 22.23.4 +,24.22.1 +,或者26.12.1 +. 下面的命令运行登录流并调用工具: ``` npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp --transport http \ --protocol-era modern \ --client-metadata-url https://app.example.com/oauth/client-metadata.json \ --method tools/call --tool-name add --tool-arg a=2 b=3 ``` `--protocol-era modern` 使检查员使用 2026 - 07 - 28 协议。默认情况下,检查员的重定向 URI 是 `http://127.0.0.1:6276/oauth/callback` (改变它与 `--callback-url`;它必须是回路地址). `--client-metadata-url` 是您主机的元数据文档的 URL, 并在此重定向 URI `redirect_uris`。授权服务器必须能够获取。对于预先注册的客户端,注册重定向的 URI 并使用 `--client-id` 相反,与 `--client-secret` 如果客户端有秘密,您也可以从客户端中连接,例如 [视觉工作室代码](<https://code.visualstudio.com/>)运行 **MCP: 添加服务器** 从命令调色板中选择 HTTP,然后输入 `http://localhost:3000/mcp`. **共同问题** - **授权服务器拒绝客户端 ID .** 它必须能够取回 `client_id` URL来自自己的网络。 如果它拥有一个信任的客户端域列表, 列表必须包含 URL 的主机 。 - **元数据文档无效 。** 其 类 `client_id` 必须与其 URL 完全相同,包括任何后端斜线。请求中的重定向 URI 必须是在 `redirect_uris`. 授权服务器应接受任何端口的回回转 IP 地址,但有些服务器也应比较端口. - **授权服务器拒绝 `resource` 数值。** 将您的服务器的 URL 注册到客户端发送时, 包括路径和任何后继斜线。 错误可能是 `invalid_target`. - **检查员的指纹 `auth_required` 成功登录后。** 您的服务器拒绝了新令牌。 命令会打印相同的信件 。 `401` 备注a `403`来看看是哪一个, 发送标志与 `curl -i -X POST http://localhost:3000/mcp -H "Content-Type: application/json" -H "Authorization: Bearer <token>"`. - **检查官在修复配置后仍然失败.** 它在运行之间保留符和客户端细节。 添加 `--relogin` 抛弃他们。 - **每一个信物都得到一个 `401`.** 解码测试符号 。 `iss` 必须是完全相同的 `ISSUER`,以及 `aud` 必须有 准确的预期受众, `http://localhost:3000/mcp` 。如果符号不是 JWT,请参见 [不透明托肯斯](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/authorization#opaque-tokens>)。检查两个服务器的时钟是否一致。 - **每一个信物都得到一个 `403`.** 如果答复有: `insufficient_scope` 错误, 符号 `scope` 索赔不包含 `mcp:tools`。一些授权服务器使用诸如: `scp`,或者用数组代替字符串。修改读取该请求的代码。如果该令牌使用的名称比客户端请求的更短,则将其转换为该词的全名。如果没有这样的错误,则使用 `Host` 或 时 间 `Origin` 信头可能被拒绝 对于一个被拒绝的人来说 `Host`, Python SDK 答案 `421` 和 ASP.NET 核心答案 `400`. - **客户拒绝启动流量.** 检查授权服务器元数据是否 `code_challenge_methods_supported` 财务报告和已审计财务报表 `issuer` 匹配 PRM 文档。 ## 常见的陷阱和如何避免它们 读取 [安保最佳做法](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices>) 攻击和如何防止攻击,以及 [安全考虑](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/security-considerations>) 这些议题在下列情况下最为重要: - **您的服务器调用其他 API**: 它必须给每个都获得一个单独的代号。 [托肯传球](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#token-passthrough>). - **您的服务器用一个静态客户端 ID 代理 OAuth**:它必须获得每个MCP客户端的用户同意。见 [被混淆的副问题](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#confused-deputy-problem>). - **您的工具返回状态控件**: 见 [州政府劫持案](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#state-handle-hijacking>). - **你建了一个客户端**: 见 [混合攻击](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#mix-up-attacks>), [OAuth 授权 URL 验证](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#oauth-authorization-url-validation>),以及 [服务器- 服务器请求伪造](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices#server-side-request-forgery-ssrf>). 以下列表涵盖了受保护服务器及其授权服务器中常见的其他错误: - **不要写你自己的符号验证**. 使用经过良好测试的图书馆进行签名检查、索赔确认和授权决定。 - **总是验证观众**。您授权服务器上正确签名的代号可能指向另一个服务。将受众与您的服务器的 URL 或您授权服务器仅用于此服务器的标识进行精确比较。不要接受多个服务器共享的值,例如 `api`. - **只接受访问符**。永远不要接受 ID 令牌。如果授权服务器跟随 [RFC 9068](<https://datatracker.ietf.org/doc/html/rfc9068>),检查该符号的 `typ` 页眉是 `at+jwt` 或 时 间 `application/at+jwt`。这些例子不检查,因为许多授权服务器使用另一个值。 - **只接受一个发行者**。拒绝其他发行人或租户的代币,除非您的服务器是多租户。 - **B. 回返面临的全部挑战**在您的 SDK 允许的情况下,包括 `resource_metadata` 财务报告和财务报告 `scope` 输入 `401` 财务报告和财务报告 `403` 列出行动需要的每个范围。 `offline_access` 克服挑战 `scopes_supported`, 因为您的服务器不需要刷新符号 。 - **返回时 `5xx` 断电期间**。如果您的服务器无法到达 JWKS 或反射端点,请返回 a `5xx` 状态, 如 TypeScript 和 Python 示例。 C# 示例只这样做, 直到它下载了一次密钥。 A `401` 让用户再次登录, 这并不能解决问题。 - **单独的客户端和服务器证书**。不要在终端用户流中使用您的 MCP 服务器的内置资质。 - **不要登录证书**删除 `Authorization` 标题、 符号、 授权代码和日志中的秘密。 将通用错误还给客户, 并将细节保存在自己的日志中 。 - **限制动态客户端注册**。如果您的授权服务器支持 [DCR](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/authorization#client-registration-approaches>) 打开 `registration_endpoint`,任何人都可以注册客户端。 如果您的客户端不依赖它, 请禁用 DCR。 否则, 请使用信任的主机等控制限制注册, 并限制费率 。 ## 相关标准和文件 MCP授权基于这些规格: - **[OAuth 2.1 (英语).](<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13>)**: 核心授权框架 - **[RFC 9728](<https://datatracker.ietf.org/doc/html/rfc9728>)**: 保护资源元数据 - **[RFC 8414](<https://datatracker.ietf.org/doc/html/rfc8414>)**: 授权服务器元数据 - **[OpenID 连接发现 1.0](<https://openid.net/specs/openid-connect-discovery-1_0.html>)**: RFC 8414的替代品 - **[RFC 8707](<https://datatracker.ietf.org/doc/html/rfc8707>)**资源指标 - **[RFC 9207](<https://datatracker.ietf.org/doc/html/rfc9207>)**: 授权服务器发行人标识 - **[OAuth 客户端 ID 元数据文档](<https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00>)**: 作为 URL 的客户端ID - **[RFC 6750](<https://datatracker.ietf.org/doc/html/rfc6750>)**: 熊鼠托肯用法 详情见: - [授权规格](<https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization>) - [安保最佳做法](<https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices>) - [授权扩展](<https://modelcontextprotocol.io/extensions/auth/overview>),用于machine-to-machine和企业管理的授权 - [可用的 MCP SDKs](<https://modelcontextprotocol.io/docs/2026-07-28/sdk>) 这页有用吗?
查看原始来源