> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.developerdoc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 授权

<div id="enable-section-numbers" />

## 引言

### 目的和范围

Model Context Protocol 在传输层提供授权能力，使 MCP 客户端能够代表资源所有者向受限 MCP 服务器发起请求。本规范定义了基于 HTTP 的传输的授权流程。

### 协议要求

授权对 MCP 实现而言是 **OPTIONAL** 的。支持授权时：

* 使用基于 HTTP 的传输的实现 **SHOULD** 遵循本规范。
* 使用 STDIO 传输的实现 **SHOULD NOT** 遵循本规范，应改为从环境中检索凭据。
* 使用替代传输的实现 **MUST** 遵循其协议已确立的安全最佳实践。

### 标准合规

该授权机制基于下列既有规范，但只实现其中选定的功能子集，以便在保持简单性的同时确保安全性和互操作性：

* OAuth 2.1 IETF DRAFT ([draft-ietf-oauth-v2-1-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13))
* OAuth 2.0 Authorization Server Metadata
  ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414))
* OAuth 2.0 Dynamic Client Registration Protocol
  ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591))
* OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728))
* OAuth Client ID Metadata Documents ([draft-ietf-oauth-client-id-metadata-document-00](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00))

## 角色

受保护的 *MCP server* 充当 [OAuth 2.1 resource server](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#name-roles)，能够使用访问 token 接受并响应受保护资源请求。

*MCP client* 充当 [OAuth 2.1 client](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#name-roles)，代表资源所有者发起受保护资源请求。

*authorization server* 负责与用户交互（如有必要），并签发可在 MCP 服务器使用的访问 token。授权服务器的实现细节超出本规范范围。它可以与资源服务器托管在一起，也可以由独立实体托管。[授权服务器发现](#authorization-server-discovery)一节规定了 MCP 服务器如何向客户端指示其对应授权服务器的位置。

## 概览

1. 授权服务器 **MUST** 实现 OAuth 2.1，并为 confidential client 和 public client 采取适当安全措施。

2. 授权服务器和 MCP 客户端 **SHOULD** 支持 OAuth Client ID Metadata Documents
   ([draft-ietf-oauth-client-id-metadata-document-00](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00)).

3. 授权服务器和 MCP 客户端 **MAY** 支持 OAuth 2.0 Dynamic Client Registration
   Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)).

4. MCP 服务器 **MUST** 实现 OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728))。
   MCP 客户端 **MUST** 使用 OAuth 2.0 Protected Resource Metadata 进行授权服务器发现。

5. MCP 授权服务器 **MUST** 至少提供以下一种发现机制：

   * OAuth 2.0 Authorization Server Metadata ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414))
   * [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html)

   MCP 客户端 **MUST** 支持这两种发现机制，以获取与授权服务器交互所需的信息。

<a id="authorization-server-discovery" />

## 授权服务器发现

本节描述 MCP 服务器向 MCP 客户端公布其关联授权服务器的机制，以及 MCP 客户端可用于确定授权服务器 endpoint 和受支持能力的发现过程。

### 授权服务器位置

MCP 服务器 **MUST** 实现 OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728)) 规范，以指示授权服务器的位置。MCP 服务器返回的 Protected Resource Metadata 文档 **MUST** 包含 `authorization_servers` 字段，且其中至少包含一个授权服务器。

`authorization_servers` 的具体使用超出本规范范围；实现者应查阅 OAuth 2.0 Protected Resource Metadata ([RFC9728](https://datatracker.ietf.org/doc/html/rfc9728))，以获取实现细节指南。

实现者应注意，Protected Resource Metadata 文档可以定义多个授权服务器。选择使用哪个授权服务器的责任由 MCP 客户端承担，并应遵循 [RFC9728 Section 7.6 "Authorization Servers"](https://datatracker.ietf.org/doc/html/rfc9728#name-authorization-servers) 中规定的指南。

### Protected Resource Metadata 发现要求

MCP 服务器 **MUST** 实现以下一种发现机制，以向 MCP 客户端提供授权服务器位置信息：

1. **WWW-Authenticate Header**：返回 `401 Unauthorized` 响应时，在 `WWW-Authenticate` HTTP header 的 `resource_metadata` 下包含资源元数据 URL，如 [RFC9728 Section 5.1](https://datatracker.ietf.org/doc/html/rfc9728#name-www-authenticate-response) 所述。

2. **Well-Known URI**：在 [RFC9728](https://datatracker.ietf.org/doc/html/rfc9728) 指定的 well-known URI 提供元数据。可以是：
   * 在服务器 MCP endpoint 的路径处：`https://example.com/public/mcp` 可在 `https://example.com/.well-known/oauth-protected-resource/public/mcp` 托管元数据
   * 在根路径处：`https://example.com/.well-known/oauth-protected-resource`

MCP 客户端 **MUST** 支持这两种发现机制，并在解析出的 `WWW-Authenticate` header 中存在资源元数据 URL 时使用它；否则，它们 **MUST** 按上面列出的顺序回退到构造并请求 well-known URI。

MCP 服务器 **SHOULD** 按 [RFC 6750 Section 3](https://datatracker.ietf.org/doc/html/rfc6750#section-3) 的定义，在 `WWW-Authenticate` header 中包含 `scope` 参数，以指示访问资源所需的 scope。这会为客户端在授权期间请求适当 scope 提供即时指导，遵循最小权限原则，并防止客户端请求过多权限。

`WWW-Authenticate` challenge 中包含的 scopes **MAY** 与 `scopes_supported` 匹配，也可以是其子集或超集，或是既非严格子集也非超集的替代集合。客户端 **MUST NOT** 假定 challenge scope 集与 `scopes_supported` 之间存在任何特定集合关系。客户端 **MUST** 将 challenge 中提供的 scopes 视为满足当前请求的权威依据。服务器 **SHOULD** 尽力以一致方式构造 scope 集，但不要求通过 `scopes_supported` 公开每个动态签发的 scope。

带有 scope 指引的 401 响应示例：

```http theme={null}
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
                         scope="files:read"
```

MCP 客户端 **MUST** 能够解析 `WWW-Authenticate` header，并适当响应来自 MCP 服务器的 `HTTP 401 Unauthorized` 响应。

如果缺少 `scope` 参数，客户端 **SHOULD** 应用 [Scope Selection Strategy](#scope-selection-strategy) 一节中定义的回退行为。

### 授权服务器元数据发现

为处理不同的 issuer URL 格式，并确保同时与 OAuth 2.0 Authorization Server Metadata 和 OpenID Connect Discovery 1.0 规范互操作，MCP 客户端在发现授权服务器元数据时 **MUST** 尝试多个 well-known endpoints。

该发现方法基于 OAuth 2.0 Authorization Server Metadata 发现所用的 [RFC8414 Section 3.1 "Authorization Server Metadata Request"](https://datatracker.ietf.org/doc/html/rfc8414#section-3.1)，以及 OpenID Connect Discovery 1.0 互操作所用的 [RFC8414 Section 5 "Compatibility Notes"](https://datatracker.ietf.org/doc/html/rfc8414#section-5)。

对于带路径组件的 issuer URL（例如 `https://auth.example.com/tenant1`），客户端 **MUST** 按以下优先级顺序尝试 endpoints：

1. 使用路径插入的 OAuth 2.0 Authorization Server Metadata：`https://auth.example.com/.well-known/oauth-authorization-server/tenant1`
2. 使用路径插入的 OpenID Connect Discovery 1.0：`https://auth.example.com/.well-known/openid-configuration/tenant1`
3. 使用路径追加的 OpenID Connect Discovery 1.0：`https://auth.example.com/tenant1/.well-known/openid-configuration`

对于不带路径组件的 issuer URL（例如 `https://auth.example.com`），客户端 **MUST** 尝试：

1. OAuth 2.0 Authorization Server Metadata: `https://auth.example.com/.well-known/oauth-authorization-server`
2. OpenID Connect Discovery 1.0：`https://auth.example.com/.well-known/openid-configuration`

### 授权服务器发现序列图

下图概述了一个示例流程：

```mermaid theme={null}
sequenceDiagram
    participant C as Client
    participant M as MCP Server (Resource Server)
    participant A as Authorization Server

    Note over C: Attempt unauthenticated MCP request
    C->>M: MCP request without token
    M-->>C: HTTP 401 Unauthorized (may include WWW-Authenticate header)

    alt Header includes resource_metadata
        Note over C: Extract resource_metadata URL from header
        C->>M: GET resource_metadata URI
        M-->>C: Resource metadata with authorization server URL
    else No resource_metadata in header
        Note over C: Fallback to well-known URI probing
        Note over M: _Not applicable if the MCP server is at the root_
        C->>M: GET /.well-known/oauth-protected-resource/mcp
        alt Sub-path metadata found
            M-->>C: Resource metadata with authorization server URL
        else Sub-path not found
            C->>M: GET /.well-known/oauth-protected-resource
            alt Root metadata found
                M-->>C: Resource metadata with authorization server URL
            else Root metadata not found
                Note over C: Abort or use pre-configured values
            end
        end
    end

    Note over C: Validate RS metadata,<br />build AS metadata URL

    C->>A: GET Authorization server metadata endpoint
    Note over C,A: Try OAuth 2.0 and OpenID Connect<br/>discovery endpoints in priority order
    A-->>C: Authorization server metadata

    Note over C,A: OAuth 2.1 authorization flow happens here

    C->>A: Token request
    A-->>C: Access token

    C->>M: MCP request with access token
    M-->>C: MCP response
    Note over C,M: MCP communication continues with valid token
```

## 客户端注册方式

MCP 支持三种客户端注册机制。请根据你的场景选择：

* **Client ID Metadata Documents**：客户端和服务器没有既有关系时使用（最常见）
* **预注册**：客户端和服务器已有关系时使用
* **Dynamic Client Registration**：用于向后兼容或特定要求

支持所有选项的客户端 **SHOULD** 遵循以下优先级顺序：

1. 如果客户端有该服务器的预注册客户端信息，则使用该信息
2. 如果授权服务器指示其支持 Client ID Metadata Documents（通过 OAuth Authorization Server Metadata 中的 `client_id_metadata_document_supported`），则使用 Client ID Metadata Documents
3. 如果授权服务器支持 Dynamic Client Registration（通过 OAuth Authorization Server Metadata 中的 `registration_endpoint`），则将其作为回退
4. 如果没有其他可用选项，则提示用户输入客户端信息

### Client ID Metadata Documents

MCP 客户端和授权服务器 **SHOULD** 支持 [OAuth Client ID Metadata Document](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00) 中规定的 OAuth Client ID Metadata Documents。该方式允许客户端使用 HTTPS URL 作为客户端标识符，其中该 URL 指向一个包含客户端元数据的 JSON 文档。这解决了 MCP 中服务器和客户端没有预先存在关系的常见场景。

#### 实现要求

支持 Client ID Metadata Documents 的 MCP 实现 **MUST** 遵循 [OAuth Client ID Metadata Document](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00) 中规定的要求。关键要求包括：

**对于 MCP 客户端：**

* 客户端 **MUST** 按 RFC 要求在 HTTPS URL 上托管其元数据文档
* `client_id` URL **MUST** 使用 "https" scheme，并包含路径组件，例如 `https://example.com/client.json`
* 元数据文档 **MUST** 至少包含以下属性：`client_id`、`client_name`、`redirect_uris`
* 客户端 **MUST** 确保元数据中的 `client_id` 值与文档 URL 完全匹配
* 客户端 **MAY** 使用 `private_key_jwt` 进行客户端身份认证（例如对 token endpoint 的请求），并配合 [Section 6.2 of Client ID Metadata Document](https://www.ietf.org/archive/id/draft-ietf-oauth-client-id-metadata-document-00.html#section-6.2) 中描述的适当 JWKS 配置

**对于授权服务器：**

* 遇到 URL 格式的 client\_ids 时 **SHOULD** 获取元数据文档
* **MUST** 验证获取到的文档中的 `client_id` 与该 URL 完全匹配
* **SHOULD** 按 HTTP cache header 缓存元数据
* **MUST** 根据元数据文档中的 redirect URIs 验证授权请求中给出的 redirect URIs
* **MUST** 验证文档结构是有效 JSON 并包含必需字段
* **SHOULD** 遵循 [Section 6 of Client ID Metadata Document](https://www.ietf.org/archive/id/draft-ietf-oauth-client-id-metadata-document-00.html#section-6) 中的安全考量

#### 元数据文档示例

```json theme={null}
{
  "client_id": "https://app.example.com/oauth/client-metadata.json",
  "client_name": "Example MCP Client",
  "client_uri": "https://app.example.com",
  "logo_uri": "https://app.example.com/logo.png",
  "redirect_uris": [
    "http://127.0.0.1:3000/callback",
    "http://localhost:3000/callback"
  ],
  "grant_types": ["authorization_code"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none"
}
```

#### Client ID Metadata Documents 流程

下图展示了使用 Client ID Metadata Documents 时的完整流程：

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Client as MCP Client
    participant Server as Authorization Server
    participant Metadata as Metadata Endpoint<br/>(Client's HTTPS URL)
    participant Resource as MCP Server

    Note over Client,Metadata: Client hosts metadata at<br/>https://app.example.com/oauth/metadata.json

    User->>Client: Initiates connection to MCP Server
    Client->>Server: Authorization Request<br/>client_id=https://app.example.com/oauth/metadata.json<br/>redirect_uri=http://localhost:3000/callback

    Server->>User: Authentication prompt
    User->>Server: Provides credentials
    Note over Server: Authenticates user

    Note over Server: Detects URL-formatted client_id

    Server->>Metadata: GET https://app.example.com/oauth/metadata.json
    Metadata-->>Server: JSON Metadata Document<br/>{client_id, client_name, redirect_uris, ...}

    Note over Server: Validates:<br/>1. client_id matches URL<br/>2. redirect_uri in allowed list<br/>3. Document structure valid<br/>4. (Optional) Domain allowed via trust policy

    alt Validation Success
        Server->>User: Display consent page with client_name
        User->>Server: Approves access
        Server->>Client: Authorization code via redirect_uri
        Client->>Server: Exchange code for token<br/>client_id=https://app.example.com/oauth/metadata.json
        Server-->>Client: Access token
        Client->>Resource: MCP requests with access token
        Resource-->>Client: MCP responses
    else Validation Failure
        Server->>User: Error response<br/>error=invalid_client or invalid_request
    end

    Note over Server: Cache metadata for future requests<br/>(respecting HTTP cache headers)
```

#### 发现

授权服务器通过在其 OAuth Authorization Server metadata 中包含以下属性，来公布其支持使用 Client ID Metadata Documents 的客户端：

```json theme={null}
{
  "client_id_metadata_document_supported": true
}
```

MCP 客户端 **SHOULD** 检查此能力；如果不可用，**MAY** 回退到 Dynamic Client Registration 或预注册。

### 预注册

MCP 客户端 **SHOULD** 支持静态客户端凭据选项，例如由预注册流程提供的凭据。这可以是：

1. 专门为 MCP 客户端与该授权服务器交互而硬编码一个 client ID（以及适用时的客户端凭据），或
2. 向用户展示一个 UI，允许他们在自行注册 OAuth client 后输入这些详情（例如通过服务器托管的配置界面）。

### Dynamic Client Registration

MCP 客户端和授权服务器 **MAY** 支持 OAuth 2.0 Dynamic Client Registration Protocol [RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)，以允许 MCP 客户端在没有用户交互的情况下获取 OAuth client ID。包含此选项是为了与 MCP 授权规范的早期版本保持向后兼容。

<a id="scope-selection-strategy" />

## Scope 选择策略

实现授权流程时，MCP 客户端 **SHOULD** 通过只请求预期操作所必需的 scopes 来遵循最小权限原则。在初始授权握手期间，MCP 客户端 **SHOULD** 按以下优先级顺序选择 scope：

1. 如果提供了初始 401 响应中 `WWW-Authenticate` header 的 `scope` 参数，则**使用 `scope` 参数**
2. **如果 `scope` 不可用**，则使用 Protected Resource Metadata 文档中 `scopes_supported` 定义的所有 scopes；如果 `scopes_supported` 未定义，则省略 `scope` 参数。

这种方式适应了 MCP 客户端的通用性质，因为 MCP 客户端通常缺少领域特定知识，无法对单个 scope 的选择作出充分判断。请求所有可用 scopes 允许授权服务器和最终用户在同意过程中确定适当权限。

这种方式在遵循最小权限原则的同时最大限度减少用户摩擦。`scopes_supported` 字段旨在表示基础功能所需的最小 scope 集（参见 [Scope 最小化](/specification/2025-11-25/basic/security_best_practices#scope-minimization)），额外 scopes 会通过 [Scope Challenge 处理](#scope-challenge-handling)一节中描述的 step-up 授权流程步骤增量请求。

## 授权流程步骤

完整授权流程如下：

```mermaid theme={null}
sequenceDiagram
    participant B as User-Agent (Browser)
    participant C as Client
    participant M as MCP Server (Resource Server)
    participant A as Authorization Server

    C->>M: MCP request without token
    M->>C: HTTP 401 Unauthorized with WWW-Authenticate header
    Note over C: Extract resource_metadata URL from WWW-Authenticate

    C->>M: Request Protected Resource Metadata
    M->>C: Return metadata

    Note over C: Parse metadata and extract authorization server(s)<br/>Client determines AS to use

    C->>A: GET Authorization server metadata endpoint
    Note over C,A: Try OAuth 2.0 and OpenID Connect<br/>discovery endpoints in priority order
    A-->>C: Authorization server metadata

    alt Client ID Metadata Documents
        Note over C: Client uses HTTPS URL as client_id
        Note over A: Server detects URL-formatted client_id
        A->>C: Fetch metadata from client_id URL
        C-->>A: JSON metadata document
        Note over A: Validate metadata and redirect_uris
    else Dynamic client registration
        C->>A: POST /register
        A->>C: Client Credentials
    else Pre-registered client
        Note over C: Use existing client_id
    end

    Note over C: Generate PKCE parameters<br/>Include resource parameter<br/>Apply scope selection strategy
    C->>B: Open browser with authorization URL + code_challenge + resource
    B->>A: Authorization request with resource parameter
    Note over A: User authorizes
    A->>B: Redirect to callback with authorization code
    B->>C: Authorization code callback
    C->>A: Token request + code_verifier + resource
    A->>C: Access token (+ refresh token)
    C->>M: MCP request with access token
    M-->>C: MCP response
    Note over C,M: MCP communication continues with valid token
```

<a id="resource-parameter-implementation" />

## Resource 参数实现

MCP 客户端 **MUST** 实现 [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) 中定义的 Resource Indicators for OAuth 2.0，以显式指定正在为其请求 token 的目标资源。`resource` 参数：

1. **MUST** 同时包含在授权请求和 token 请求中。
2. **MUST** 标识客户端打算将该 token 用于哪个 MCP 服务器。
3. **MUST** 使用 [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707.html#name-access-token-request) 中定义的 MCP 服务器规范 URI。

### 规范服务器 URI

就本规范而言，MCP 服务器的规范 URI 定义为 [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707.html#section-2) 中规定的资源标识符，并与 [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) 中的 `resource` 参数保持一致。

MCP 客户端 **SHOULD** 按 [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707) 中的指南，为其打算访问的 MCP 服务器提供尽可能具体的 URI。虽然规范形式使用小写 scheme 和 host 组件，但实现 **SHOULD** 接受大写 scheme 和 host 组件，以提高稳健性和互操作性。

有效规范 URI 示例：

* `https://mcp.example.com/mcp`
* `https://mcp.example.com`
* `https://mcp.example.com:8443`
* `https://mcp.example.com/server/mcp`（当需要路径组件来标识单个 MCP 服务器时）

无效规范 URI 示例：

* `mcp.example.com`（缺少 scheme）
* `https://mcp.example.com#fragment`（包含 fragment）

> **注意：** 虽然根据 [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986)，`https://mcp.example.com/`（带尾随斜杠）和 `https://mcp.example.com`（不带尾随斜杠）在技术上都是有效的绝对 URI，但除非尾随斜杠对特定资源具有语义意义，否则实现 **SHOULD** 一致使用不带尾随斜杠的形式以获得更好的互操作性。

例如，如果访问位于 `https://mcp.example.com` 的 MCP 服务器，授权请求将包含：

```
&resource=https%3A%2F%2Fmcp.example.com
```

无论授权服务器是否支持该参数，MCP 客户端 **MUST** 发送它。

## Access Token 使用

### Token 要求

向 MCP 服务器发起请求时的 access token 处理 **MUST** 符合 [OAuth 2.1 Section 5 "Resource Requests"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5) 中定义的要求。具体而言：

1. MCP 客户端 **MUST** 使用 [OAuth 2.1 Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5.1.1) 中定义的 Authorization 请求 header 字段：

```
Authorization: Bearer <access-token>
```

请注意，从客户端到服务器的每个 HTTP 请求中都 **MUST** 包含授权信息，即使它们属于同一个逻辑会话。

2. Access tokens **MUST NOT** 包含在 URI query string 中

请求示例：

```http theme={null}
GET /mcp HTTP/1.1
Host: mcp.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

### Token 处理

作为 OAuth 2.1 resource server，MCP 服务器 **MUST** 按 [OAuth 2.1 Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5.2) 中的描述验证 access token。MCP 服务器 **MUST** 按 [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707.html#section-2) 验证 access token 是专门以它们为预期 audience 签发的。如果验证失败，服务器 **MUST** 按 [OAuth 2.1 Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5.3) 的错误处理要求进行响应。无效或过期的 token **MUST** 收到 HTTP 401 响应。

MCP 客户端 **MUST NOT** 向 MCP 服务器发送并非由该 MCP 服务器的授权服务器签发的 token。

MCP 服务器 **MUST** 只接受对其自身资源有效的 token。

MCP 服务器 **MUST NOT** 接受或转发任何其他 token。

## 错误处理

服务器 **MUST** 为授权错误返回适当的 HTTP 状态码：

| 状态码 | 说明           | 用法             |
| --- | ------------ | -------------- |
| 401 | Unauthorized | 需要授权或 token 无效 |
| 403 | Forbidden    | scopes 无效或权限不足 |
| 400 | Bad Request  | 授权请求格式错误       |

<a id="scope-challenge-handling" />

### Scope Challenge 处理

本节介绍在运行时操作中处理 insufficient scope 错误的方式，此时客户端已经拥有 token 但需要额外权限。这遵循 [OAuth 2.1 Section 5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5) 中定义的错误处理模式，并利用 [RFC 9728 (OAuth 2.0 Protected Resource Metadata)](https://datatracker.ietf.org/doc/html/rfc9728) 中的元数据字段。

#### 运行时 Insufficient Scope 错误

当客户端在运行时操作中使用 scope 不足的 access token 发起请求时，服务器 **SHOULD** 以以下内容响应：

* `HTTP 403 Forbidden` status code（按 [RFC 6750 Section 3.1](https://datatracker.ietf.org/doc/html/rfc6750#section-3.1)）
* 带有 `Bearer` scheme 和额外参数的 `WWW-Authenticate` header：
  * `error="insufficient_scope"` - 指示具体授权失败类型
  * `scope="required_scope1 required_scope2"` - 指定该操作所需的最小 scopes
  * `resource_metadata` - Protected Resource Metadata 文档的 URI（用于与 401 响应保持一致）
  * `error_description`（可选）- 人类可读的错误描述

**服务器 Scope 管理**：响应 insufficient scope 错误时，服务器 **SHOULD** 在 `scope` 参数中包含满足当前请求所需的 scopes。

服务器可以灵活决定包含哪些 scopes：

* **最小方式**：包含该特定操作新要求的 scopes。如果还需要任何已授予的现有 scopes，也一并包含，以防客户端丢失先前授予的权限。
* **推荐方式**：同时包含现有相关 scopes 和新要求的 scopes，以防客户端丢失先前授予的权限
* **扩展方式**：包含现有 scopes、新要求的 scopes，以及通常一起使用的相关 scopes

选择哪种方式取决于服务器对用户体验影响和授权摩擦的评估。

服务器 **SHOULD** 在其 scope 包含策略上保持一致，为客户端提供可预测行为。

服务器在确定响应中包含哪些 scopes 时 **SHOULD** 考虑用户体验影响，因为配置错误的 scopes 可能要求用户频繁交互。

insufficient scope 响应示例：

```http theme={null}
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope",
                         scope="files:read files:write user:profile",
                         resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
                         error_description="Additional file write permission required"
```

#### Step-Up 授权流程

客户端会在初始授权期间或运行时收到 scope 相关错误（`insufficient_scope`）。客户端 **SHOULD** 通过 step-up authorization flow 请求具有更大 scope 集的新 access token 来响应这些错误，或以其他适当方式处理错误。代表用户行事的客户端 **SHOULD** 尝试 step-up authorization flow。代表自身行事的客户端（`client_credentials` 客户端）**MAY** 尝试 step-up authorization flow，或立即中止请求。

流程如下：

1. 从授权服务器响应或 `WWW-Authenticate` header 中**解析错误信息**
2. 按 [Scope Selection Strategy](#scope-selection-strategy) 中所述**确定所需 scopes**。
3. 使用确定的 scope 集**发起（重新）授权**
4. 使用新授权**重试原始请求**，但最多只重试少数几次；之后将其视为永久授权失败

客户端 **SHOULD** 实现重试限制，并且 **SHOULD** 跟踪 scope 升级尝试，以避免同一资源和操作组合反复失败。

## 安全考量

实现 **MUST** 遵循 [OAuth 2.1 第 7 节“安全考量”](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#name-security-considerations) 中阐述的 OAuth 2.1 安全最佳实践。

### Token Audience 绑定和验证

在**授权服务器支持该能力时**，[RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) Resource Indicators 通过将 token 绑定到其预期 audience 来提供关键安全收益。为支持当前和未来采用：

* MCP 客户端 **MUST** 按 [Resource 参数实现](#resource-parameter-implementation)一节中的规定，在授权和 token 请求中包含 `resource` 参数
* MCP 服务器 **MUST** 验证提交给它们的 token 是专门为其使用而签发的

[安全最佳实践文档](/specification/2025-11-25/basic/security_best_practices#token-passthrough)概述了为什么 token audience 验证至关重要，以及为什么明确禁止 token passthrough。

### Token 窃取

攻击者如果获得客户端存储的 token，或服务器缓存或记录的 token，就可以用看似对资源服务器合法的请求访问受保护资源。

客户端和服务器 **MUST** 实现安全 token 存储，并遵循 [OAuth 2.1, Section 7.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-7.1) 中概述的 OAuth 最佳实践。

授权服务器 **SHOULD** 签发短生命周期 access token，以降低 token 泄露的影响。对于 public client，授权服务器 **MUST** 按 [OAuth 2.1 Section 4.3.1 "Token Endpoint Extension"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-4.3.1) 中的描述轮换 refresh token。

### 通信安全

实现 **MUST** 遵循 [OAuth 2.1 Section 1.5 "Communication Security"](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-1.5)。

具体而言：

1. 所有授权服务器 endpoints **MUST** 通过 HTTPS 提供服务。
2. 所有 redirect URIs **MUST** 是 `localhost` 或使用 HTTPS。

### 授权码保护

获得授权响应中授权码的攻击者可以尝试将授权码兑换为 access token，或以其他方式利用授权码。（详见 [OAuth 2.1 Section 7.5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-7.5)）

为缓解此问题，MCP 客户端 **MUST** 按 [OAuth 2.1 Section 7.5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-7.5.2) 实现 PKCE，并且 **MUST** 在继续授权前验证 PKCE 支持。PKCE 要求客户端创建秘密的 verifier-challenge 对，确保只有原始请求方可以将授权码交换为 token，从而帮助防止授权码拦截和注入攻击。

在技术上可行时，MCP 客户端 **MUST** 使用 `S256` code challenge method，如 [OAuth 2.1 Section 4.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-4.1.1) 所要求。

由于 OAuth 2.1 和 PKCE 规范未定义客户端发现 PKCE 支持的机制，MCP 客户端 **MUST** 依赖授权服务器元数据来验证此能力：

* **OAuth 2.0 Authorization Server Metadata**：如果缺少 `code_challenge_methods_supported`，则授权服务器不支持 PKCE，MCP 客户端 **MUST** 拒绝继续。

* **OpenID Connect Discovery 1.0**：虽然 [OpenID Provider Metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata) 未定义 `code_challenge_methods_supported`，但 OpenID provider 通常会包含该字段。MCP 客户端 **MUST** 验证 provider 元数据响应中存在 `code_challenge_methods_supported`。如果缺少该字段，MCP 客户端 **MUST** 拒绝继续。

提供 OpenID Connect Discovery 1.0 的授权服务器 **MUST** 在其元数据中包含 `code_challenge_methods_supported`，以确保 MCP 兼容性。

### 开放重定向

攻击者可能构造恶意 redirect URIs，将用户引导到钓鱼网站。

MCP 客户端 **MUST** 在授权服务器注册 redirect URIs。

授权服务器 **MUST** 根据预注册值精确验证 redirect URIs，以防止重定向攻击。

MCP 客户端 **SHOULD** 在授权码流程中使用并验证 state 参数，并丢弃任何不包含原始 state 或与原始 state 不匹配的结果。

授权服务器 **MUST** 按 [OAuth 2.1 Section 7.12.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-7.12.2) 中的建议采取预防措施，防止将 user agents 重定向到不受信任的 URI。

授权服务器 **SHOULD** 仅在信任 redirection URI 时自动重定向 user agent。如果 URI 不受信任，授权服务器 **MAY** 告知用户，并依赖用户作出正确决定。

### Client ID Metadata Document 安全

实现 Client ID Metadata Documents 时，授权服务器 **MUST** 考虑 [OAuth Client ID Metadata Document, Section 6](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#name-security-considerations) 中详述的安全影响。关键考量包括：

#### 授权服务器滥用保护

授权服务器会从未知客户端接收 URL 作为输入并获取该 URL。恶意客户端可利用这一点触发授权服务器向任意 URL 发起请求，例如请求授权服务器可访问的私有管理 endpoints。

获取元数据文档的授权服务器 **SHOULD** 考虑 [Server-Side Request Forgery (SSRF)](https://developer.mozilla.org/docs/Web/Security/Attacks/SSRF) 风险，如 [OAuth Client ID Metadata Document: Server Side Request Forgery (SSRF) Attacks](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#name-server-side-request-forgery) 中所述。

#### Localhost Redirect URI 风险

Client ID Metadata Documents 本身无法防止 `localhost` URL 冒充。攻击者可以通过以下方式声称自己是任意客户端：

1. 将合法客户端的元数据 URL 作为其 `client_id` 提供
2. 绑定到任意 `localhost` 端口，并将该地址作为 redirect\_uri 提供
3. 在用户批准时通过重定向接收授权码

服务器会看到合法客户端的元数据文档，用户也会看到合法客户端的名称，从而使攻击难以检测。

授权服务器：

* **SHOULD** 对仅使用 `localhost` 的 redirect URIs 显示额外警告
* **MAY** 要求额外 attestations 机制以增强安全性
* **MUST** 在授权期间清晰显示 redirect URI hostname

#### 信任策略

授权服务器 **MAY** 实现基于域名的信任策略：

* 针对受信任域的 allowlist（用于受保护服务器）
* 接受任何 HTTPS `client_id`（用于开放服务器）
* 对未知域进行信誉检查
* 基于域名年龄或证书验证的限制
* 显著显示 CIMD 和其他关联客户端 hostname，以防钓鱼

服务器对其访问策略保持完全控制。

<a id="confused-deputy-problem" />

### Confused Deputy 问题

攻击者可以利用充当第三方 API 中介的 MCP 服务器，导致 [confused deputy 漏洞](/specification/2025-11-25/basic/security_best_practices#confused-deputy-problem)。通过使用窃取的授权码，他们可以在未经用户同意的情况下获得 access token。

使用静态 client ID 的 MCP 代理服务器 **MUST** 在转发到第三方授权服务器（可能需要额外同意）之前，为每个动态注册客户端获得用户同意。

### Access Token 权限限制

如果服务器接受为其他资源签发的 token，攻击者可能获得未授权访问，或以其他方式危害 MCP 服务器。

该漏洞有两个关键维度：

1. **Audience 验证失败。** 当 MCP 服务器未验证 token 是否专门面向它（例如通过 [RFC9068](https://www.rfc-editor.org/rfc/rfc9068.html) 中提到的 audience claim）时，它可能接受原本为其他服务签发的 token。这打破了基本的 OAuth 安全边界，允许攻击者跨越预期之外的不同服务重用合法 token。
2. **Token passthrough。** 如果 MCP 服务器不仅接受 audience 不正确的 token，还将这些未修改的 token 转发给下游服务，就可能导致 ["confused deputy" problem](#confused-deputy-problem)，即下游 API 可能错误地信任该 token，仿佛它来自 MCP 服务器，或假定该 token 已由上游 API 验证。更多详情见安全最佳实践指南中的 [Token Passthrough section](/specification/2025-11-25/basic/security_best_practices#token-passthrough)。

MCP 服务器 **MUST** 在处理请求前验证 access token，确保 access token 是专门为该 MCP 服务器签发的，并采取所有必要措施确保不会向未授权方返回数据。

MCP 服务器 **MUST** 遵循 [OAuth 2.1 - Section 5.2](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#section-5.2) 中的指南来验证入站 token。

MCP 服务器 **MUST** 只接受专门面向自身的 token，并且 **MUST** 拒绝未在 audience claim 中包含自身的 token，或以其他方式验证自己是该 token 的预期接收方。详情请参见[安全最佳实践 Token Passthrough 小节](/specification/2025-11-25/basic/security_best_practices#token-passthrough)。

如果 MCP 服务器向上游 API 发起请求，它可以作为面向这些 API 的 OAuth client。上游 API 使用的 access token 是由上游授权服务器签发的独立 token。MCP 服务器 **MUST NOT** 透传它从 MCP 客户端收到的 token。

MCP 客户端 **MUST** 实现并使用 [RFC 8707 - Resource Indicators for OAuth 2.0](https://www.rfc-editor.org/rfc/rfc8707.html) 中定义的 `resource` 参数，以显式指定正在为其请求 token 的目标资源。该要求与 [RFC 9728 Section 7.4](https://datatracker.ietf.org/doc/html/rfc9728#section-7.4) 中的建议一致。这可确保 access token 绑定到其预期资源，不能被跨不同服务误用。

## MCP 授权扩展

核心协议有若干授权扩展，用于定义额外授权机制。这些扩展具有以下特点：

* **可选** - 实现可以选择采用这些扩展
* **增量** - 扩展不会修改或破坏核心协议功能；它们在保留核心协议行为的同时添加新能力
* **可组合** - 扩展是模块化的，并被设计为可以无冲突地协同工作，允许实现同时采用多个扩展
* **独立版本化** - 扩展遵循核心 MCP 版本周期，但可按需采用独立版本

支持的扩展列表可在 [MCP Authorization Extensions](https://github.com/modelcontextprotocol/ext-auth) 仓库中找到。
