MCP Gateway 为符合规范的 MCP 客户端实现了 OAuth 2.1 + PKCE 认证。
这是 Claude Desktop 和 MCP Inspector 等交互式桌面应用的推荐认证方式。
流程概览
第一步:动态客户端注册
注册新的 OAuth 客户端。按照 MCP Authorization 规范,仅支持公开客户端
(无 client_secret)。
curl -s -X POST "https://mcp.beeos.ai/oauth/register" \
-H "Content-Type: application/json" \
-d '{
"client_name": "my-mcp-client",
"redirect_uris": ["http://localhost:5173/callback"]
}' | jq
响应:
{
"client_id": "mcp_client_abc123",
"client_name": "my-mcp-client",
"redirect_uris": ["http://localhost:5173/callback"]
}
第二步:授权请求
生成 PKCE code verifier 和 challenge,然后重定向用户:
GET https://mcp.beeos.ai/oauth/authorize
?client_id=mcp_client_abc123
&redirect_uri=http://localhost:5173/callback
&response_type=code
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
&state=random_state_value
Gateway 将浏览器重定向到 BeeOS Web 应用登录页。用户认证后,浏览器会
重定向回你的 redirect_uri 并附带授权码:
http://localhost:5173/callback?code=auth_code_xyz&state=random_state_value
第三步:令牌交换
将授权码兑换为访问令牌:
curl -s -X POST "https://mcp.beeos.ai/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "code=auth_code_xyz" \
-d "client_id=mcp_client_abc123" \
-d "redirect_uri=http://localhost:5173/callback" \
-d "code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" | jq
响应:
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600
}
第四步:使用令牌
在 MCP 请求中携带访问令牌:
curl -s -X POST "https://mcp.beeos.ai/${AGENT_ID}/mcp" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
发现端点
MCP 客户端使用以下众所周知的端点来发现 OAuth 服务器:
| 端点 | 用途 |
|---|
GET /.well-known/oauth-authorization-server | OAuth 2.1 授权服务器元数据 (RFC 8414) |
GET /.well-known/oauth-protected-resource | MCP 受保护资源元数据(指向 AS) |
curl -s "https://mcp.beeos.ai/.well-known/oauth-authorization-server" | jq
令牌详情
| 属性 | 值 |
|---|
| 算法 | HS256 |
| 默认 TTL | 60 分钟 |
| 授权码 TTL | 120 秒 |
| 客户端类型 | 仅公开(无 client_secret) |
授权码在 120 秒后过期。请在重定向回调后立即兑换。
401 响应行为
当请求认证失败时,Gateway 返回:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="MCP", resource_metadata="/.well-known/oauth-protected-resource"
符合规范的 MCP 客户端使用 resource_metadata URL 来发现授权服务器
并自动启动 OAuth 流程。