跳到內容

MCP Authorization 與 OAuth 2.1

Model Context Protocol(MCP) 是一個標準化協定,讓 AI 應用程式能夠與外部工具和資料來源互動。當 MCP Server 需要授權保護時,規範選擇直接採用 OAuth 2.0 生態系的標準,而非自己發明新的授權機制。

MCP 的授權是選擇性的(OPTIONAL),僅適用於 HTTP-based transport。使用 STDIO transport 的實作應從環境變數取得憑證。

MCP 的使用場景帶來了三個具體的授權需求,分別對應不同的 OAuth 標準:

需求對應標準
Client 不知道 Server 的授權端點在哪裡Authorization Server Metadata(RFC 8414)
Client 無法事先向每個 Server 註冊Dynamic Client Registration(RFC 7591)
使用者要安全地授權 Client 存取 Server 資源OAuth 2.1 + PKCE

MCP Client 可能隨時連接全新的 Server,不可能事先知道每個 Server 的授權端點。RFC 8414 讓 Client 自動發現這些資訊。

Client 向 Server 的 well-known 端點發送請求:

GET /.well-known/oauth-authorization-server HTTP/1.1
Host: api.example.com
MCP-Protocol-Version: 2025-03-26

Server 回傳 Metadata 文件,包含 Authorization Endpoint、Token Endpoint、Registration Endpoint 等位置。

如果 Server 不支援 Metadata Discovery(回傳 404),Client 使用預設路徑:

端點預設路徑
Authorization Endpoint/authorize
Token Endpoint/token
Registration Endpoint/register

Authorization Base URL 取自 MCP Server URL 的 domain,忽略 path。例如 Server 在 https://api.example.com/v1/mcp,端點就在 https://api.example.com/authorize

MCP 規範要求 Client 必須實作 Metadata Discovery,Server 應該實作。

傳統 OAuth 應用由開發者事先到 Provider 管理介面註冊,取得 client_id。但 MCP Client 面對的是不確定數量的 Server,手動註冊不切實際。

RFC 7591 讓 Client 程式化地向 Server 註冊:

POST /register HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"client_name": "My AI Assistant",
"redirect_uris": ["http://localhost:3000/callback"],
"grant_types": ["authorization_code"],
"response_types": ["code"],
"token_endpoint_auth_method": "none"
}

Server 回傳 client_id,Client 就能進入授權流程。

不支援 Dynamic Client Registration 的 Server,需要提供替代方式讓 Client 取得 client_id(硬編碼或讓使用者手動輸入)。

取得端點位置和 client_id 後,MCP Client 執行標準的 Authorization Code + PKCE 流程。MCP 規範的具體要求:

  • PKCE 為必要:所有 Client 都必須使用,不論是 Public 或 Confidential Client
  • 每個請求都帶 TokenAuthorization: Bearer 必須出現在每個 HTTP 請求中
  • Token 不放 URL:Access Token 不得放在 query string 中
  • 401 觸發授權:Server 在需要授權時回傳 HTTP 401,Client 收到後啟動 OAuth 流程

MCP Server 依使用情境支援不同的 Grant Type:

Grant Type場景
Authorization CodeAI 助理代表使用者呼叫 SaaS 工具
Client CredentialsAI Agent 自己存取資源,不涉及使用者

MCP Server 不一定要自己當 Authorization Server,也可以委派給第三方(如 Google、GitHub)。此時 MCP Server 同時扮演兩個角色:對 MCP Client 而言是 Authorization Server,對第三方而言是 OAuth Client。

流程是兩段式的授權碼交換,MCP Server 最終產生自己的 Access Token,綁定到第三方的 Session。