跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

授权

最后更新 查看 MarkdownAgent 设置

构建 Model Context Protocol (MCP) ↗ server 时,既需要让用户登录(authentication),也需要让用户授权 MCP client 访问其账户上的资源(authorization)。

Model Context Protocol 使用 OAuth 2.1 的子集进行授权 ↗。OAuth 允许用户授予有限资源访问权限,而无需共享 API 密钥或其他凭据。

Cloudflare 的 Workers OAuth Provider ↗ 在 Workers 上实现了 MCP 授权的两端。一次部署包含两种角色:

  • 授权服务器负责为用户登录并签发访问令牌。使用 OAuthAuthorizationServer 构建。
  • 资源服务器就是你的 MCP 服务器。它接受这些令牌,并通过 Service Binding 向授权服务器检查每个令牌。使用 OAuthResourceServer 包装 createMcpHandler 构建。
sequenceDiagram
    participant C as MCP client
    participant M as MCP server (resource server)
    participant A as Authorization server

    C->>M: MCP request without a token
    M->>C: 401, pointing at the protected resource metadata
    C->>A: Sign in and authorize (/authorize, /oauth/token)
    A->>C: Access token for the MCP server
    C->>M: MCP request with the access token
    M->>A: validateToken() over the Service Binding
    A->>M: Token details and the props stored at sign-in
    M->>C: MCP response

一个授权服务器可以为多个 MCP 服务器签发令牌,而每个服务器都可以在自己的 Worker 中运行。

构建授权服务器

为授权服务器创建一个 Worker 并安装此库:

npm i @cloudflare/workers-oauth-provider

该库提供发现、客户端注册和 token 端点。/authorize 页面由你负责:它用于登录用户、征求同意并调用 completeAuthorization()。你在那里传递的 props 会被加密,并随每个请求传递给 MCP 服务器。

auth-server/src/index.jsjs
import {
	AuthorizationError,
	OAuthAuthorizationServer,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";

// Everything this server can grant.
const SCOPES = ["mcp:read", "mcp:write", "offline_access"];

const authorizationServer = new OAuthAuthorizationServer({
	issuer: env.ISSUER, // this Worker's URL
	resources: [env.MCP_SERVER_URL], // the MCP servers it issues tokens for
	scopesSupported: SCOPES,
	clientIdMetadataDocumentEnabled: true,
	// Optional: Dynamic Client Registration for older MCP clients.
	clientRegistrationEndpoint: "/oauth/register",
});

async function authorize(request, env) {
	const oauth = authorizationServer.getOAuthApi(env);

	let authRequest;
	try {
		// Validates the client, redirect URI, resource, and PKCE.
		authRequest = await oauth.parseAuthRequest(request);
	} catch (error) {
		if (!(error instanceof AuthorizationError)) throw error;
		if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
		return new Response(error.description, { status: 400 });
	}

	// Replace with your own sign-in and consent page.
	const user = { id: "user-123", name: "Ada" };

	const { redirectTo } = await oauth.completeAuthorization({
		request: authRequest,
		userId: user.id,
		metadata: {},
		scope: authRequest.scope.filter((scope) => SCOPES.includes(scope)),
		props: { userId: user.id, name: user.name },
	});
	return Response.redirect(redirectTo, 302);
}

export default class AuthServer extends WorkerEntrypoint {
	fetch(request) {
		if (new URL(request.url).pathname === "/authorize") {
			return authorize(request, this.env);
		}
		return authorizationServer.fetch(request, this.env, this.ctx);
	}

	// MCP servers call this over their Service Binding.
	validateToken(resource, token) {
		return authorizationServer.validateToken(resource, token, this.env);
	}
}
auth-server/src/index.tsts
import {
    AuthorizationError,
    OAuthAuthorizationServer,
    type AuthRequest,
} from "@cloudflare/workers-oauth-provider";
import { env, WorkerEntrypoint } from "cloudflare:workers";

// Everything this server can grant.
const SCOPES = ["mcp:read", "mcp:write", "offline_access"];

const authorizationServer = new OAuthAuthorizationServer<Env>({
    issuer: env.ISSUER, // this Worker's URL
    resources: [env.MCP_SERVER_URL], // the MCP servers it issues tokens for
    scopesSupported: SCOPES,
    clientIdMetadataDocumentEnabled: true,
    // Optional: Dynamic Client Registration for older MCP clients.
    clientRegistrationEndpoint: "/oauth/register",
});

async function authorize(request: Request, env: Env): Promise<Response> {
    const oauth = authorizationServer.getOAuthApi(env);

    let authRequest: AuthRequest;
    try {
        // Validates the client, redirect URI, resource, and PKCE.
        authRequest = await oauth.parseAuthRequest(request);
    } catch (error) {
        if (!(error instanceof AuthorizationError)) throw error;
        if (error.redirectTo) return Response.redirect(error.redirectTo, 302);
        return new Response(error.description, { status: 400 });
    }

    // Replace with your own sign-in and consent page.
    const user = { id: "user-123", name: "Ada" };

    const { redirectTo } = await oauth.completeAuthorization({
        request: authRequest,
        userId: user.id,
        metadata: {},
        scope: authRequest.scope.filter((scope) => SCOPES.includes(scope)),
        props: { userId: user.id, name: user.name },
    });
    return Response.redirect(redirectTo, 302);
}

export default class AuthServer extends WorkerEntrypoint<Env> {
    fetch(request: Request) {
        if (new URL(request.url).pathname === "/authorize") {
            return authorize(request, this.env);
        }
        return authorizationServer.fetch(request, this.env, this.ctx);
    }

    // MCP servers call this over their Service Binding.
    validateToken(resource: string, token: string) {
        return authorizationServer.validateToken(resource, token, this.env);
    }
}

授权服务器会将授权许可和 token 存储在绑定为 OAUTH_KV 的 KV 命名空间中。运行 npx wrangler kv namespace create OAUTH_KV 创建一个命名空间。Client ID Metadata Documents 需要 global_fetch_strictly_public 标志,因为服务器会获取客户端提供的 URL。

{
    "name": "auth-server",
    "main": "src/index.ts",
    // Set this to today's date
    "compatibility_date": "2026-11-20",
    "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
    "vars": {
        "ISSUER": "https://auth-server.<your-subdomain>.workers.dev",
        "MCP_SERVER_URL": "https://mcp-server.<your-subdomain>.workers.dev/mcp",
    },
    "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "<YOUR_KV_NAMESPACE_ID>" }],
}
name = "auth-server"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-11-20"
compatibility_flags = [ "nodejs_compat", "global_fetch_strictly_public" ]

[vars]
ISSUER = "https://auth-server.<your-subdomain>.workers.dev"
MCP_SERVER_URL = "https://mcp-server.<your-subdomain>.workers.dev/mcp"

[[kv_namespaces]]
binding = "OAUTH_KV"
id = "<YOUR_KV_NAMESPACE_ID>"

将 MCP 服务器设为资源服务器

使用 OAuthResourceServer 包装 createMcpHandler 处理程序。它会发布 MCP 客户端用于查找授权服务器的受保护资源元数据;对于没有有效 token 的请求,它会返回 401;对于为其他资源签发的 token,它会予以拒绝。只有 token 有效时才会运行你的处理程序。

mcp-server/src/index.jsjs
import {
	OAuthResourceServer,
	insufficientScope,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

function createServer() {
	const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" });
	const props = getMcpAuthContext()?.props;

	server.registerTool(
		"whoami",
		{ description: "Return the signed-in user" },
		async () => ({
			content: [{ type: "text", text: `Hello, ${props.name}!` }],
		}),
	);

	return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer({
	resourceMetadata: {
		resource: env.MCP_SERVER_URL, // the URL MCP clients connect to
		authorization_servers: [env.AUTH_SERVER_URL],
	},
	// Scopes every client must ask for. Advertised, not enforced: check them in the handler.
	requiredScopes: ["mcp:read"],
	validateToken: (env) => env.AUTH_SERVER.validateToken,
	handler: {
		fetch(request, env, ctx) {
			if (!ctx.auth.scope.includes("mcp:read")) {
				return insufficientScope(ctx.auth, ["mcp:read"]);
			}
			// ctx.props is what completeAuthorization() stored.
			// createMcpHandler exposes it to tools through getMcpAuthContext().
			return mcpHandler(request, env, ctx);
		},
	},
});
mcp-server/src/index.tsts
import {
    OAuthResourceServer,
    insufficientScope,
    type AuthorizationServerBinding,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

type AuthProps = { userId: string; name: string };

interface Env {
    AUTH_SERVER: AuthorizationServerBinding<AuthProps>;
    AUTH_SERVER_URL: string;
    MCP_SERVER_URL: string;
}

function createServer() {
    const server = new McpServer({ name: "my-mcp-server", version: "1.0.0" });
    const props = getMcpAuthContext()?.props as AuthProps;

    server.registerTool(
        "whoami",
        { description: "Return the signed-in user" },
        async () => ({
            content: [{ type: "text", text: `Hello, ${props.name}!` }],
        }),
    );

    return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer<Env, AuthProps>({
    resourceMetadata: {
        resource: env.MCP_SERVER_URL, // the URL MCP clients connect to
        authorization_servers: [env.AUTH_SERVER_URL],
    },
    // Scopes every client must ask for. Advertised, not enforced: check them in the handler.
    requiredScopes: ["mcp:read"],
    validateToken: (env) => env.AUTH_SERVER.validateToken,
    handler: {
        fetch(request, env, ctx) {
            if (!ctx.auth.scope.includes("mcp:read")) {
                return insufficientScope(ctx.auth, ["mcp:read"]);
            }
            // ctx.props is what completeAuthorization() stored.
            // createMcpHandler exposes it to tools through getMcpAuthContext().
            return mcpHandler(request, env, ctx);
        },
    },
});

MCP 服务器通过 Service Binding 访问授权服务器,因此 token 检查不会离开 Cloudflare 网络,而且 MCP 服务器无需自己的 KV 命名空间:

{
    "name": "mcp-server",
    "main": "src/index.ts",
    // Set this to today's date
    "compatibility_date": "2026-11-20",
    "compatibility_flags": ["nodejs_compat"],
    "vars": {
        "AUTH_SERVER_URL": "https://auth-server.<your-subdomain>.workers.dev",
        "MCP_SERVER_URL": "https://mcp-server.<your-subdomain>.workers.dev/mcp",
    },
    "services": [{ "binding": "AUTH_SERVER", "service": "auth-server" }],
}
name = "mcp-server"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-11-20"
compatibility_flags = [ "nodejs_compat" ]

[vars]
AUTH_SERVER_URL = "https://auth-server.<your-subdomain>.workers.dev"
MCP_SERVER_URL = "https://mcp-server.<your-subdomain>.workers.dev/mcp"

[[services]]
binding = "AUTH_SERVER"
service = "auth-server"

先部署授权服务器,因为 MCP 服务器需要绑定到它。然后部署 MCP 服务器,并将 MCP 客户端连接到其 /mcp URL。客户端会根据 401 响应转到授权服务器,让用户登录,然后携带 token 重试。

MCP_SERVER_URL 必须与客户端连接的 URL 完全一致,因为每个 token 都绑定到该 URL。要进行本地开发,请在不同端口上分别对每个 Worker 运行 npx wrangler dev,并在各 Worker 的 .dev.vars 文件中将 URL 设置为对应的 http://localhost 地址。此库仅在回环主机上接受 http。

登录用户

/authorize 页面应仅在用户登录并批准客户端后调用 completeAuthorization()。该库提供了以下辅助函数:

  • 同意页面:describeConsent()、beginConsent()、approveConsent() 和 denyConsent() 可构建无法被框架嵌入或伪造的同意页面。请参阅构建同意页面 ↗。
  • 通过 GitHub、Google 或其他提供程序登录:beginUpstream() 和 finishUpstream() 会在用户同意后将其发送到提供程序,并在提供程序重定向回来时完成登录。将提供程序的访问 token 存储在 props 中,以便从工具调用其 API。请参阅通过其他提供程序登录 ↗。

Cloudflare Access

Cloudflare Access 可以为登录 MCP 服务器的用户提供身份验证。用户通过已配置的身份提供程序或一次性 PIN进行身份验证,只有符合你的 Access 策略的用户才会获准访问。请参阅使用 Access for SaaS 保护 MCP 服务器。

身份提供程序

你也可以使用现有的身份提供程序登录用户。它可以定义与工具对应的范围,并显示自己的同意页面。

Stytch

从使用 Stytch 的远程 MCP 服务器 ↗ 开始,让用户通过邮件、Google 登录或企业 SSO 登录,并授权其 AI Agent 代表其查看与管理公司 OKR。Stytch 会根据用户在组织内的角色与权限,限制授予 AI Agent 的范围。MCP 客户端授权时,每位用户会看到同意页,列出根据其角色可授予 Agent 的权限。

部署到 Cloudflare

更多面向消费者的用例:部署用于待办应用的远程 MCP 服务器,使用 Stytch 进行身份验证与 MCP 客户端授权。用户可通过邮件登录并立即访问账户关联的待办列表,并授权任意 AI 助手帮助管理任务。

部署到 Cloudflare

Auth0

从使用 Auth0 的远程 MCP 服务器开始,让用户通过邮件、社交登录或企业 SSO 认证,并通过 AI Agent 与其待办与个人数据交互。MCP 服务器代表用户安全连接 API 端点,并准确展示 Agent 在用户同意后能访问的资源。此实现中,访问令牌在长时间交互期间会自动刷新。

设置步骤:首先部署受保护的 API 端点:

部署到 Cloudflare

然后部署通过 Auth0 处理身份验证、并将 AI Agent 安全连接到你 API 端点的 MCP 服务器。

部署到 Cloudflare

WorkOS

从使用 WorkOS AuthKit 的远程 MCP 服务器开始,认证用户并管理授予 AI Agent 的权限。此示例中,MCP 服务器根据用户角色与访问权限动态暴露工具。所有已认证用户可使用 add 工具,但仅在 WorkOS 中被分配 image_generation 权限的用户才能授权 AI Agent 访问图像生成工具。这展示了 MCP 服务器如何根据已认证用户的角色与权限有条件地向 AI Agent 暴露能力。

部署到 Cloudflare

Descope

开始使用采用 Descope ↗ Agentic Identity Hub 的远程 MCP 服务器,通过身份验证和授权让用户(例如通过电子邮件、社交登录或 SSO)使用 AI 代理访问其数据。在 Descope 的 MCP Server 资源上定义范围,以便按工具精细管理权限。

部署到 Cloudflare

有关所有选项,请参阅 Workers OAuth Provider 文档 ↗。如果你运行的是现有的 OAuthProvider 部署(在一个 Worker 中组合两种角色),请参阅 1.x 迁移指南 ↗。

在工具中使用身份验证上下文

你传递给 completeAuthorization() 的 props 会作为 ctx.props 到达资源服务器处理程序,而 createMcpHandler 会通过 getMcpAuthContext() 将其提供给服务器。已验证 token 的范围和客户端信息可在处理程序中的 ctx.auth 读取。

MCP 服务器示例中的 whoami 工具会以这种方式读取 props.name。

Props 通常包含上游访问令牌。请勿记录或返回这些令牌。

基于权限的 tool 访问

你可以根据用户权限控制哪些工具可用。有两种方式:在工具处理程序中检查权限,或仅为有权限使用工具的用户注册工具。getMcpAuthContext() 可在服务器工厂中使用,因此工厂可以决定针对每个请求注册哪些工具。

import {
	OAuthResourceServer,
	insufficientScope,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

// Stored with completeAuthorization() when the user signed in.

function createServer() {
	const server = new McpServer({ name: "Permissions Demo", version: "1.0.0" });
	const props = getMcpAuthContext()?.props;

	server.registerTool(
		"publicTool",
		{ description: "Available to all users" },
		async () => ({
			content: [{ type: "text", text: "Public result" }],
		}),
	);

	// Check inside the handler: the model sees the tool and the denial.
	server.registerTool(
		"adminAction",
		{ description: "Requires admin permission" },
		async () => {
			if (!props.permissions.includes("admin")) {
				return {
					isError: true,
					content: [
						{ type: "text", text: "Permission denied: requires admin" },
					],
				};
			}
			return {
				content: [{ type: "text", text: "Admin action completed" }],
			};
		},
	);

	// Register conditionally: the model never sees the tool.
	if (props.permissions.includes("special_feature")) {
		server.registerTool(
			"specialTool",
			{ description: "Special feature" },
			async () => ({
				content: [{ type: "text", text: "Special feature result" }],
			}),
		);
	}

	return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer({
	resourceMetadata: {
		resource: env.MCP_SERVER_URL,
		authorization_servers: [env.AUTH_SERVER_URL],
	},
	requiredScopes: ["mcp:read"],
	validateToken: (env) => env.AUTH_SERVER.validateToken,
	handler: {
		fetch(request, env, ctx) {
			if (!ctx.auth.scope.includes("mcp:read")) {
				return insufficientScope(ctx.auth, ["mcp:read"]);
			}
			return mcpHandler(request, env, ctx);
		},
	},
});
import {
    OAuthResourceServer,
    insufficientScope,
    type AuthorizationServerBinding,
} from "@cloudflare/workers-oauth-provider";
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler, getMcpAuthContext } from "agents/mcp/server";
import { env } from "cloudflare:workers";

// Stored with completeAuthorization() when the user signed in.
type AuthProps = { userId: string; permissions: string[] };

interface Env {
    AUTH_SERVER: AuthorizationServerBinding<AuthProps>;
}

function createServer() {
    const server = new McpServer({ name: "Permissions Demo", version: "1.0.0" });
    const props = getMcpAuthContext()?.props as AuthProps;

    server.registerTool(
        "publicTool",
        { description: "Available to all users" },
        async () => ({
            content: [{ type: "text", text: "Public result" }],
        }),
    );

    // Check inside the handler: the model sees the tool and the denial.
    server.registerTool(
        "adminAction",
        { description: "Requires admin permission" },
        async () => {
            if (!props.permissions.includes("admin")) {
                return {
                    isError: true,
                    content: [
                        { type: "text", text: "Permission denied: requires admin" },
                    ],
                };
            }
            return {
                content: [{ type: "text", text: "Admin action completed" }],
            };
        },
    );

    // Register conditionally: the model never sees the tool.
    if (props.permissions.includes("special_feature")) {
        server.registerTool(
            "specialTool",
            { description: "Special feature" },
            async () => ({
                content: [{ type: "text", text: "Special feature result" }],
            }),
        );
    }

    return server;
}

const mcpHandler = createMcpHandler(createServer);

export default new OAuthResourceServer<Env, AuthProps>({
    resourceMetadata: {
        resource: env.MCP_SERVER_URL,
        authorization_servers: [env.AUTH_SERVER_URL],
    },
    requiredScopes: ["mcp:read"],
    validateToken: (env) => env.AUTH_SERVER.validateToken,
    handler: {
        fetch(request, env, ctx) {
            if (!ctx.auth.scope.includes("mcp:read")) {
                return insufficientScope(ctx.auth, ["mcp:read"]);
            }
            return mcpHandler(request, env, ctx);
        },
    },
});

在处理程序内部检查权限会向 LLM 返回错误消息,LLM 可以向用户说明拒绝原因。按条件注册工具则意味着 LLM 根本看不到用户无权访问的工具,因此也无法尝试调用它们。

若要改为按 OAuth 范围控制访问权限,请在资源服务器处理程序中检查 ctx.auth.scope,并在缺少某个范围时返回 insufficientScope(ctx.auth, [...])。随后客户端会请求用户授予额外范围并重试。要在工具中使用范围,请在调用 completeAuthorization() 时将已授予的范围存储在 props 中。

后续步骤

MCP 门户

设置 MCP 门户以提供治理与安全。

这篇文档对您有帮助吗?