理解 MCP 中的授权
模型上下文协议(MCP)中的授权用于保护对 MCP 服务器所暴露敏感资源和操作的访问。如果你的 MCP 服务器处理用户数据或管理操作,授权可以确保只有被允许的用户才能访问其端点。
MCP 授权遵循 OAuth 2.1,可以与任何满足其要求的授权或身份系统协同工作。本指南先解释整个流程,再演示如何保护一个小型服务器。完整要求见授权规范。
何时应使用授权?
MCP 服务器的授权是可选的。在以下情况下强烈建议使用:
- 你的服务器处理用户特定数据,例如电子邮件、文档或数据库
- 你需要审计谁执行了哪些操作
- 你的服务器授予对其 API 的访问权限,而这些 API 需要用户同意
- 你正在为具有严格访问控制的企业环境构建应用
- 你想要实现按用户限流或使用量跟踪
本地 MCP 服务器的授权
本指南中的 OAuth 流程面向基于 HTTP 的传输。使用 stdio 传输 的服务器应改为从环境获取凭据。它们在本地运行,也可以使用内嵌在服务器中的库所提供的凭据。
授权流程:分步详解
流程中有三方参与。你的 MCP 服务器是一个 OAuth 资源服务器:在这个角色里它验证访问 token,而不签发 token。MCP 客户端是代表用户行事的 OAuth 客户端。授权服务器对用户进行身份验证,并为你的 MCP 服务器签发 token。它可以是独立服务,也可以与 MCP 服务器托管在一起。
sequenceDiagram
participant B as Browser
participant C as MCP Client
participant M as MCP Server
participant A as Authorization Server
C->>M: MCP request without a token
M-->>C: 401 with WWW-Authenticate
C->>M: GET Protected Resource Metadata
M-->>C: authorization_servers, scopes_supported
C->>A: GET authorization server metadata
A-->>C: Endpoints and capabilities
Note over C,A: Client identifies itself:<br/>pre-registered ID, metadata document, or DCR
Note over C: Record the issuer
C->>B: Open authorization URL<br/>(PKCE challenge, resource, scope)
B->>A: User logs in and consents
A-->>B: Redirect with code and iss
B->>C: Authorization code
Note over C: Validate iss
C->>A: Code, PKCE verifier, resource
A-->>C: Access token for this MCP server
C->>M: MCP request with the token
M-->>C: MCP response
初始请求
客户端发来的请求没有有效 token 时,你的服务器以 401 Unauthorized 响应。WWW-Authenticate 头可以指向受保护资源元数据(PRM)文档,并应同时给出访问该资源所需的 scope。
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://your-server.com/.well-known/oauth-protected-resource/mcp",
scope="mcp:tools"客户端应请求质询中列出的 scope。质询未列出时,应请求 PRM 文档 scopes_supported 中的全部内容;如果它也缺失,则省略 scope 参数。见scope 选择策略。
服务器必须包含 resource_metadata 指针,或在 well-known URI 上提供 PRM 文档,两者可以同时使用。指针缺失时,客户端先尝试 /.well-known/oauth-protected-resource 加上 MCP 端点的路径,再尝试去掉路径的同一 URL。见受保护资源元数据发现要求。
受保护资源元数据发现
客户端获取 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 节规定:resource 不匹配时,客户端不得使用该文档。
授权服务器发现
客户端选定一个授权服务器并获取其元数据。元数据可以位于 OAuth 2.0 授权服务器元数据或 OpenID Connect 发现URL。客户端必须同时支持两者,并按规范定义的顺序尝试这些 URL。
{
"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 的 issuer 标识符完全一致。不一致时,客户端不得使用该文档。code_challenge_methods_supported必须存在。缺失时客户端必须拒绝继续,因为该授权服务器不支持 PKCE。
客户端注册
客户端需要一个授权服务器接受的 client ID。可选方式总结见客户端注册方式。
用户授权
客户端在浏览器中打开 authorization_endpoint。请求携带 PKCE code_challenge 和 resource 参数(RFC 8707),后者设为 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 和 state 重定向回客户端。如果它支持 RFC 9207,还会返回 iss。
打开浏览器之前,客户端必须记下已验证元数据中的 issuer。交换授权码之前,它必须验证 iss 与该 issuer 一致,两个值都不得做归一化。如果授权服务器声明支持 iss,客户端必须拒绝缺失 iss 的响应。错误响应也适用同一检查;检查失败时,客户端不得处理或展示该错误。
客户端还应丢弃 state 缺失或与发送值不同的响应。
随后客户端把授权码、PKCE verifier 和同一个 resource 值发往 token_endpoint。它收到一个访问 token,授权服务器也可以选择同时返回刷新 token:
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "mcp:tools"
}发起经过身份验证的请求
客户端在每个 HTTP 请求的 Authorization 头中携带访问 token,绝不放在 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 服务器验证 token 并检查它是否为本服务器签发。无效或过期的 token 得到 401。
token 有效但缺少 scope 时,服务器应响应 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"客户端随后应发起升步授权流程(step-up):请求质询中的 scope 加上此前请求过的 scope,并限制重试频率。
客户端注册方式
| 方式 | 适用场景 |
|---|---|
| 预注册 | 客户端已持有该授权服务器的凭据 |
| 客户端 ID 元数据文档 | 客户端与服务器事先没有关系(最常见) |
| 动态客户端注册 | 已弃用。用于不支持客户端 ID 元数据文档的授权服务器 |
同时支持三种方式的客户端应按上述顺序尝试。全都不可用时,应请用户手动输入客户端信息。见客户端注册。
客户端 ID 元数据文档
使用客户端 ID 元数据文档(Client ID Metadata Document,CIMD)时,客户端把一个 HTTPS URL 当作自己的 client_id,并在该 URL 上托管一份 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 声明支持。只要授权服务器支持 CIMD,客户端就可以在所有这类服务器上复用同一个 client ID;你的 MCP 服务器更换授权服务器时,它不需要重新注册。
预注册
client ID(以及需要时的凭据)提前设置好,可以内置于客户端,也可以由用户输入。
动态客户端注册
使用 DCR 时,客户端把自身元数据 POST 到授权服务器的 registration_endpoint 并收到一个 client ID。客户端必须包含合适的 application_type:
{
"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",
"application_type": "native"
}预注册和 DCR 凭据属于签发它们的授权服务器。客户端必须按 issuer 分别存储,绝不能在另一个授权服务器上使用。见授权服务器绑定。
选择授权服务器
使用现成的身份提供方或授权服务器产品。客户端注册发生在客户端与授权服务器之间,你的 MCP 服务器不需要任何 CIMD 或 DCR 代码。
选择之前核对以下几点:
- Audience。 你的 MCP 服务器必须拒绝不是为它签发的 token。客户端传来的
resource值应成为 token 的 audience(JWT 中的aud声明)。有些产品需要专门设置,或允许在 scope 上配置 audience;另一些永远使用自己的标识符,此时拿该标识符做比较,并把你服务器的 URL 继续作为 PRM 的resource。该标识符必须只属于这一个 MCP 服务器,不要在多个服务器之间共用一个应用注册。 - 元数据。 必须通过 RFC 8414 或 OpenID Connect Discovery 提供元数据,且元数据必须包含
code_challenge_methods_supported。要看真实文档:有些产品支持 PKCE 却漏掉这个值,遵循规范的客户端会因此拒绝连接。 - CIMD。 应支持 CIMD(以
client_id_metadata_document_supported声明)。某些产品需要手动开启,或要配置接受客户端的域名列表。 - token 格式。 下面的示例需要签名的 JWT 访问 token;否则你需要内省端点。
- 公共客户端。 很多 MCP 客户端没有密钥。授权服务器必须接受它们,
token_endpoint_auth_methods_supported应包含none。 - scope。 定义一个类似
mcp:tools的 scope,并让将要连接的客户端可以获取它。有些产品会给 scope 名加前缀;如果是这样,把示例中所有mcp:tools都换成完整名称。定义多个 scope 时,阅读scope 最小化,scopes_supported中只列出基本使用所需的 scope。 - token 生命周期。 访问 token 应短生命周期,因为被窃取的 token 在过期前一直可用。授权服务器必须为公共客户端轮换刷新 token。
- 响应中的 issuer。 应在授权响应中返回
iss;如果支持,必须声明authorization_response_iss_parameter_supported。
本地测试
你可以在自己的机器上运行授权服务器。例如 Keycloak 对 CIMD 和资源指示符有实验性支持:用 --features=cimd,resource-indicators 启动即可同时开启两者。之后你还需要为 CIMD 创建客户端策略,并把服务器 URL 加进它的资源指示符允许列表。
实现示例
下面的示例保护一个只有一个工具 add 的 MCP 服务器。每个服务器都运行在 http://localhost:3000/mcp,要求 mcp:tools scope,并接受 RS256 签名的 JWT 访问 token。运行前先改掉这些值:
ISSUER是授权服务器元数据中issuer的精确值。METADATA_URL是该元数据的 URL。issuer 含路径时(如https://auth.example.com/tenant1),RFC 8414 URL 是https://auth.example.com/.well-known/oauth-authorization-server/tenant1,OpenID Connect URL 通常是https://auth.example.com/tenant1/.well-known/openid-configuration。RS256(C# 中是RsaSha256)是签名算法,授权服务器使用其他算法时替换它。Python 中公开密钥必须带有alg值。mcp:tools是必需的 scope。- 期望的 audience 是服务器 URL。授权服务器把自己的标识符放进
aud时替换它。它对应 TypeScript 与 Python 的audience选项、C# 的ValidAudience。
C# 示例中前两项叫 issuer 和 metadataUrl。TypeScript 与 Python 示例在启动时获取元数据,授权服务器不可达时直接退出。
TypeScript
安装 TypeScript SDK 包、一个 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在 package.json 中设置 "type": "module",然后创建 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在/.well-known/oauth-protected-resource/mcp提供 PRM 文档,并为在 MCP 服务器上查找该元数据的旧客户端镜像授权服务器元数据。requireBearerAuth对每个请求运行你的验证器:token 缺失或无效时回答401质询,缺少 scope 时回答403质询。jwtVerify检查签名、issuer、audience 和生命周期。保留它的audience选项,因为expectedResource不查看 token。expectedResource在验证器报告了其他 resource 或没有 resource 时拒绝该 token。它要求@modelcontextprotocol/express2.0.2,更早的版本会忽略它。createMcpExpressApp对绑定到 localhost 的服务器校验Host和Origin头。
运行服务器:
npx tsx server.ts为单个工具要求 scope 的做法,见 TypeScript SDK 文档中的 Require authorization。
Python
安装 Python SDK、HTTPX2,以及 RS256 所需的带 crypto 扩展的 PyJWT:
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 在
/.well-known/oauth-protected-resource/mcp提供 PRM 文档,内容由AuthSettings生成。 verify_token返回None会产生401质询。缺少required_scopes之一的 token 得到403质询。jwt.decode检查签名、issuer、audience 和生命周期。保留它的audience参数,因为validate_token_resource不查看 token。它让 SDK 在AccessToken.resource不是resource_server_url时拒绝该 token。它要求 2.2 版本,更早的版本会忽略它。- SDK 不把
scope放进质询。401之后,客户端从scopes_supported中找到 scope;403之后,有些客户端只请求已有的 scope,升步授权可能拿不到缺失的 scope。
运行服务器:
python server.py更多细节见 Python SDK 文档中的 Authorization。
C#
此示例使用 C# SDK 和 ASP.NET Core 在 .NET 10 上的 JWT bearer 身份验证。创建 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在/.well-known/oauth-protected-resource/mcp提供 PRM 文档。AddJwtBearer下载签名密钥并验证签名、issuer、audience 和生命周期。默认它在 token 过期后五分钟内仍然接受,所以示例设置了ClockSkew。示例设置MetadataAddress是因为Authority选项只查找 OpenID Connect Discovery 元数据。mcp:tools策略强制检查 scope。单独的RequireAuthorization()会接受任何有效 token。OnChallenge和OnForbidden写出401和403质询。SDK 自带的401质询没有scope,在代理之后其resource_metadataURL 可能出错;它不发送403质询。- JWT bearer 身份验证只通过 HTTPS 下载元数据。使用其他 URL 时请求以
500失败。如果本地授权服务器使用明文 HTTP,在AddJwtBearer中设置options.RequireHttpsMetadata = false,且只能在开发环境这么做。 OnAuthenticationFailed让服务器在从未成功下载签名密钥时回答500;没有它,ASP.NET Core 会回答401。- ASP.NET Core 每 12 小时或在遇到未知密钥时重新下载签名密钥。下载完成前它对未知密钥回答
401。默认此操作每五分钟至多一次,新密钥可能被拒绝这么久;示例设置RefreshInterval来缩短它。 - 传输规范要求服务器校验
Origin头。SDK 不做这件事,示例在中间件里完成。
运行服务器:
dotnet run使用 [Authorize] 做按工具授权的做法,见 C# SDK 文档中的 Identity and Role Propagation。工具上的 [Authorize] 检查失败时返回 JSON-RPC 错误而不是 403 质询,客户端无法据此发起升步授权。
不透明 token
如果你的授权服务器签发不透明 token(opaque token),改用它的 token 内省端点,而不是验证 JWT。该端点的 URL 是元数据中的 introspection_endpoint 值。
该端点要求身份验证,所以你的 MCP 服务器需要自己在授权服务器上的凭据。如果使用 HTTP Basic 身份验证,先对 client ID 和 secret 做 form 编码。该凭据必须被允许内省此服务器的 token;不允许时,有效 token 的响应中 active 也会是 false。
active 为 false 时拒绝该 token。为 true 时,先确认 aud 包含期望的 audience,再把 resource 报告给 SDK;scope 和 exp 也要检查。这些值在 RFC 中是可选的,务必确认你的授权服务器返回它们,并拒绝 aud 缺失的 token。端点不可达或返回错误状态(包括 401)时,按故障处理。
如果缓存 token 或结果,加密 token,并在不晚于 token 过期时删除每个条目。把服务器的凭据保存在机密管理器中。
TypeScript 与 Python 中,这个调用放在验证器里。C# 中,把 AddJwtBearer 换成支持内省的身份验证处理器。
部署到 localhost 之外
把服务器 URL 改成客户端连接的精确 https URL。它同时用作 PRM 的 resource 和期望的 audience。路径不是 /mcp 时,路由也要改:TypeScript 中是 app.all 的路径,Python 中是 mcp.run 的 streamable_http_path 参数,C# 示例从 URL 推导。TypeScript 中,new URL() 会给没有路径的 URL 补上尾斜杠,token 的 aud 就必须包含它。
客户端必须通过 HTTPS 访问你的服务器。示例服务的是明文 HTTP,把它们放到终结 TLS 并保留原始 Host 头的反向代理或负载均衡器之后。代理在同一台机器上时,继续只监听 localhost,仅修改接受的 host 与 origin。
示例只监听 localhost 并拒绝其他 Host 头的请求。按需配置接受的 host 和浏览器 origin:
- TypeScript:向
createMcpExpressApp传host、allowedHosts和allowedOrigins,并修改app.listen的地址。两个列表中的 host 名不带 scheme 和端口。没有浏览器客户端连接时传空的allowedOrigins列表,因为 SDK 没有它就不检查Origin。设置NODE_ENV=production,避免 Express 把堆栈跟踪发给客户端。 - Python:向
mcp.run传host和作为transport_security的TransportSecuritySettings对象,从mcp.server.transport_security导入该类,并设置allowed_hosts和allowed_origins。改了host却省略它时,SDK 两个头都不检查。host 必须与Host头完全一致(带端口时包括端口),origin 必须包含 scheme。条目以:*结尾表示接受任意端口。 - C#:把
app.Run的 URL 改成监听地址(如http://0.0.0.0:3000);修改allowedOrigins(条目含 scheme)和allowedHosts(条目不含 scheme 和端口)。
接受某个 origin 并不等于启用了 CORS。浏览器中运行的客户端还需要在身份验证之前应答预检请求、并暴露 WWW-Authenticate 头的 CORS 中间件。
本协议修订没有会话。只支持该修订的服务器可以忽略 Mcp-Session-Id 头;如果它还接受旧客户端,绝不要把会话 ID 当作调用者身份的证明。见 2025-11-25 规范中的会话劫持。
测试服务器
先检查发现。这些请求不需要 token:
curl -i -X POST http://localhost:3000/mcp
curl http://localhost:3000/.well-known/oauth-protected-resource/mcp第一条命令应打印带 WWW-Authenticate 头的 401;第二条应打印 PRM 文档,其中包含你服务器的 URL 和你的 issuer。
同时打开你的 METADATA_URL,确认其中包含 code_challenge_methods_supported。有些客户端没有它也能工作,有些会拒绝连接。
然后用 MCP Inspector(需要 Node.js 22.19 或更高)跑完整流程。下面的命令会打开浏览器登录并调用工具:
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 让 Inspector 使用 2026-07-28 协议。
Inspector 的重定向 URI 是 http://127.0.0.1:6276/oauth/callback。--client-metadata-url 是你托管的元数据文档的 URL,其 redirect_uris 必须包含该重定向 URI。如果你的授权服务器支持 DCR 且接受来自你机器的注册,可以省略此选项。预注册客户端则注册该重定向 URI 并改用 --client-id,客户端有密钥时再加 --client-secret。
也可以从 Visual Studio Code 这类客户端连接:在命令面板中运行 MCP: Add Server,选择 HTTP 并输入 http://localhost:3000/mcp。
常见问题
- 授权服务器拒绝 client ID。 它必须能从自己的网络获取该
client_idURL。如果它有受信任客户端域名列表,列表必须包含该 URL 的主机。 - 元数据文档无效。 文档的
client_id必须与其 URL 完全一致(包括尾斜杠)。请求中的重定向 URI 必须在redirect_uris中。授权服务器应接受环回 IP 地址的任意端口,但有些会比较端口。 - 授权服务器拒绝
resource值。 按客户端发送的精确形式注册你服务器的 URL,包括路径和尾斜杠。错误可能是invalid_target。 - 登录成功后 Inspector 打印
auth_required。 你的服务器拒绝了新 token。401和403会打印同样的消息。要区分它们,用curl -i -X POST http://localhost:3000/mcp -H "Content-Type: application/json" -H "Authorization: Bearer <token>"直接发送该 token。 - 修复配置后 Inspector 仍然失败。 它会在多次运行之间保留 token 和已注册的客户端。加
--relogin丢弃它们。 - 每个 token 都得到
401。 解码一个测试 token。iss必须与ISSUER完全相同,aud必须恰好包含期望的 audience(示例中是http://localhost:3000/mcp)。token 不是 JWT 时,见不透明 token。同时检查两台服务器的时钟是否一致。 - 每个 token 都得到
403。 响应带insufficient_scope错误时,token 的scope声明不含mcp:tools。有些授权服务器用scp之类的声明名,或用数组而不是字符串——修改读取该声明的代码;token 中的名称比客户端请求的短时,也在那里换算成完整名称。没有这类错误时,可能是Host或Origin头被拒绝。Host被拒绝时 Python SDK 回答421,ASP.NET Core 回答400。 - 客户端拒绝启动流程。 检查授权服务器元数据中有
code_challenge_methods_supported,且其issuer与 PRM 文档一致。
常见陷阱及规避方法
攻击方式与防范手段请阅读安全最佳实践,规范中的强制要求见安全注意事项。以下情形最值得注意:
- 你的服务器调用其他 API:必须为每个 API 单独获取 token。见token 透传。
- 你的服务器用单个静态 client ID 代理 OAuth:必须为每个 MCP 客户端获得用户同意。见混淆代理人问题。
- 你的工具返回状态句柄:见状态句柄劫持。
- 你在构建客户端:见混淆攻击、OAuth 授权 URL 验证和服务器端请求伪造。
下面列出受保护服务器及其授权服务器中的其他常见错误:
- 不要自行编写 token 验证。签名检查、声明验证和授权决策都使用经过充分测试的库。
- 始终验证 audience。来自你授权服务器的、签名正确的 token 也可能是发给其他服务的。把 audience 与你服务器的 URL、或授权服务器专为此服务器使用的标识符精确比较。不要接受多个服务器共用的值,例如
api。 - 只接受访问 token。绝不接受 ID token。授权服务器遵循 RFC 9068 时,检查 token 的
typ头是at+jwt或application/at+jwt。示例没有检查它,因为很多授权服务器使用其他值。 - 只接受一个 issuer。拒绝来自其他 issuer 或租户的 token,除非你的服务器就是多租户的。
- 返回完整的质询。SDK 允许时,在
401和403质询中包含resource_metadata和scope。一次列出操作需要的全部 scope。offline_access不要放进质询和scopes_supported,因为你的服务器不需要刷新 token。 - 故障期间返回
5xx。服务器无法访问 JWKS 或内省端点时,返回5xx状态,就像 TypeScript 和 Python 示例那样;C# 示例只在尚未下载过密钥时如此。401会让用户重新登录,而那解决不了问题。 - 分开客户端与服务器凭据。不要把 MCP 服务器的内省凭据用在最终用户流程里。
- 不要记录凭据。从日志中移除
Authorization头、token、授权码和机密。向客户端返回通用错误,细节留在你自己的日志里。 - 限制动态客户端注册。开放的
registration_endpoint意味着任何人都能注册,加上受信任主机、速率限制等控制。
相关标准与文档
MCP 授权建立在以下规范之上:
- OAuth 2.1:核心授权框架
- RFC 9728:受保护资源元数据
- RFC 8414:授权服务器元数据
- OpenID Connect Discovery 1.0:RFC 8414 的替代方案
- RFC 8707:资源指示符
- RFC 9207:授权服务器 issuer 识别
- OAuth Client ID Metadata Document:URL 形式的 client ID
- RFC 7591:动态客户端注册
- RFC 6750:Bearer token 用法
更多细节请参阅:
- 授权规范
- 安全最佳实践
- 授权扩展,用于机器对机器和企业托管授权
- 可用的 MCP SDK