跳到主内容

为您的 MCP 服务器设置 Casdoor

本指南说明如何将 Casdoor 设置为您自己的 MCP 服务器的授权服务器:首先是 Casdoor 中的配置,然后是您的 MCP 服务器的更改。


学习目标​

  • 为您的 MCP 服务器创建带有自定义作用域的应用。
  • 让 MCP 客户端自行注册。
  • 发布 Protected Resource Metadata 并质询未认证的请求。
  • 在您的工具中验证令牌并强制执行作用域。

所需条件​

  • 一个正在运行的 Casdoor 实例及其管理员访问权限。参见 安装 Casdoor 服务器。
  • 您的 MCP 服务器的公共 URL,例如 https://your-mcp-server.com

配置 Casdoor​

创建应用​

  1. 在 Casdoor 管理控制台中,前往 Identity > Applications 并添加一个应用。

  2. 填写 Basic 选项卡:

    FieldValue
    NameA descriptive name, for example my-files-mcp-server
    OrganizationThe organization whose users use the MCP server
    CategoryAgent. This turns on custom scopes. See Application categories
    TypeMCP. Casdoor sets it when you select Agent

添加重定向 URL​

将使用您服务器的 MCP 客户端的回调 URL 添加到 Redirect URLs,例如 https://mcp.example.com/oauth/callback。Casdoor 会在授权后将用户发送回这些 URL。

Casdoor 接受完全等于某个条目的重定向 URL。否则,对于带有协议的条目,协议、主机、端口和路径必须匹配。主机的子域名也视为匹配,当两个 URL 都使用相同的回环主机(如 localhost 或 127.0.0.1)时,Casdoor 会忽略端口。不带协议的条目(例如 example.com/callback)匹配该主机或其子域名的 http 和 https URL;前导点(如 .example.com)仅匹配子域名,不带路径的条目匹配任意路径。如果条目无法解析为 URL(例如包含 \.),Casdoor 将其视为正则表达式,要求整个 URL 与之匹配。通过动态客户端注册自行注册的客户端会携带自己的重定向 URL,因此无需在此处添加这些 URL。

设置授权类型​

在 Grant types 中,开启:

  • Authorization Code:MCP 使用的流程。
  • Refresh Token:允许客户端保持登录状态而无需重新授权。

保持隐式授权和密码授权关闭。MCP 不使用它们。

定义作用域​

为工具的每个功能定义一个作用域。

  1. 在 Scopes 中,为每个作用域添加一行:

    ColumnValue
    NameThe scope in the form resource:action, for example files:read
    Display nameA short name for users, for example Read Files
    描述What the scope allows. Users read it on the consent screen
  2. 保存应用。

对于文件服务器,作用域可以是:

Name显示名称描述
files:read读取文件查看和下载存储中的文件
files:write写文件在您的存储中创建、修改和删除文件
files:list列出文件查看目录中的文件名和元数据

对于数据库服务器:

Name显示名称Description
db:query查询数据库执行只读数据库查询
db:modify修改数据库创建、更新和删除数据库记录
db:admin数据库管理管理表结构、数据表和数据库设置

保持作用域的细粒度,以便用户可以授予部分访问权限。从少量作用域开始,随着工具的增长再添加更多。参见 定义自定义作用域。

由于应用定义了自定义作用域,当客户端请求用户尚未授予的作用域时,Casdoor 会显示一个同意屏幕。该屏幕列出了作用域及其显示名称和描述。Casdoor 会记住此授权,用户和管理员可以在 Consents 页面上撤销它。

允许动态客户端注册​

Claude Desktop 等 MCP 客户端会在首次使用时自行注册。要允许此操作:

  1. 打开客户端将在其中注册的组织的编辑页面。如果注册 URL 中没有 organization 参数,则默认为 built-in。
  2. 开启 Enable dynamic client registration 并保存。

随后任何人都可以通过 /api/oauth/register 注册客户端。请参阅动态注册客户端。

检查发现 URL​

您的 MCP 服务器使用以下 Casdoor URL:

URLPurpose
https://your-casdoor.com/.well-known/oauth-authorization-serverAuthorization Server Metadata
https://your-casdoor.com/.well-known/openid-configurationOpenID Connect Discovery
https://your-casdoor.com/.well-known/jwksPublic keys for token validation

检查它们是否有响应:

# Check OAuth metadata
curl https://your-casdoor.com/.well-known/oauth-authorization-server

# Check OIDC discovery
curl https://your-casdoor.com/.well-known/openid-configuration

# Check JWKS (JSON Web Key Set for token validation)
curl https://your-casdoor.com/.well-known/jwks

配置 MCP 服务器​

发布受保护资源元数据​

在 GET /.well-known/oauth-protected-resource 处提供以下 JSON 文档:

{
"resource": "https://your-mcp-server.com",
"authorization_servers": ["https://your-casdoor.com"],
"scopes_supported": [
"files:read",
"files:write",
"files:list"
],
"bearer_methods_supported": ["header"]
}
FieldValue
resourcePublic URL of your MCP server. Tokens for your server carry it in the aud claim
authorization_serversThe URL of Casdoor
scopes_supportedThe scopes that you defined in Casdoor
bearer_methods_supported["header"]. Clients send the token in the Authorization header

在 Python Flask 中:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/.well-known/oauth-protected-resource')
def protected_resource_metadata():
return jsonify({
"resource": "https://your-mcp-server.com",
"authorization_servers": ["https://your-casdoor.com"],
"scopes_supported": ["files:read", "files:write", "files:list"],
"bearer_methods_supported": ["header"]
})

在 Node.js Express 中:

const express = require('express');
const app = express();

app.get('/.well-known/oauth-protected-resource', (req, res) => {
res.json({
resource: 'https://your-mcp-server.com',
authorization_servers: ['https://your-casdoor.com'],
scopes_supported: ['files:read', 'files:write', 'files:list'],
bearer_methods_supported: ['header']
});
});

在 Go net/http 中:

package main

import (
"encoding/json"
"net/http"
)

type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
ScopesSupported []string `json:"scopes_supported"`
BearerMethodsSupported []string `json:"bearer_methods_supported"`
}

func protectedResourceHandler(w http.ResponseWriter, r *http.Request) {
metadata := ProtectedResourceMetadata{
Resource: "https://your-mcp-server.com",
AuthorizationServers: []string{"https://your-casdoor.com"},
ScopesSupported: []string{"files:read", "files:write", "files:list"},
BearerMethodsSupported: []string{"header"},
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(metadata)
}

func main() {
http.HandleFunc("/.well-known/oauth-protected-resource", protectedResourceHandler)
http.ListenAndServe(":8080", nil)
}

对未认证请求进行挑战​

当请求没有有效的令牌时,返回 HTTP 401 状态码和一个 WWW-Authenticate 标头,其 resource_metadata 参数指向您的元数据文档:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="MCP Server", resource_metadata="https://your-mcp-server.com/.well-known/oauth-protected-resource"
Content-Type: application/json

正文内容如下所示:

{
"error": "unauthorized",
"message": "Authentication required. Use OAuth 2.0 with the authorization server listed in the Protected Resource Metadata."
}

验证令牌​

对于每个包含 Bearer 令牌的请求:

  1. 从 Authorization: Bearer <token> 标头中提取令牌。
  2. 从 https://your-casdoor.com/.well-known/jwks 获取公钥。缓存这些密钥并定期刷新缓存。
  3. 使用匹配的密钥验证令牌的签名。
  4. 检查 aud 声明是否为服务器的资源 URI,例如 https://your-mcp-server.com。
  5. 检查 exp 声明是否在未来。
  6. 从 scope 声明中读取作用域,这是一个以空格分隔的字符串。

完整代码请参见在 MCP 服务器中验证 Casdoor 令牌。

在工具中强制执行作用域​

在每个工具执行任何操作之前检查所需的作用域。例如,read_file 工具需要 files:read:

def read_file(token_scopes, file_path):
if "files:read" not in token_scopes:
raise PermissionError("Missing required scope: files:read")

# Proceed with file reading
with open(file_path, 'r') as f:
return f.read()

当缺少作用域时返回清晰的错误,并记录授权失败情况。

验证设置​

  1. 请求元数据文档:

    curl https://your-mcp-server.com/.well-known/oauth-protected-resource

    预期输出:

    {
    "resource": "https://your-mcp-server.com",
    "authorization_servers": ["https://your-casdoor.com"],
    "scopes_supported": ["files:read", "files:write"],
    "bearer_methods_supported": ["header"]
    }
  2. 发送不带令牌的请求:

    curl -i https://your-mcp-server.com/api/mcp

    预期响应:

    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: Bearer realm="MCP Server", resource_metadata="https://your-mcp-server.com/.well-known/oauth-protected-resource"
  3. 将 Claude Desktop 等 MCP 客户端连接到 https://your-mcp-server.com。客户端通过元数据找到 Casdoor,将您重定向到 Casdoor 登录页面,在您同意后,携带令牌调用您的工具。

故障排除​

Casdoor 报告无效的重定向 URL​

客户端的重定向 URL 不在应用的 Redirect URLs 中,或者与之不完全匹配。添加准确的 URL。对于自行注册的客户端,请检查其 dcr_ 应用的重定向 URL。

无法验证令牌签名​

  • 使用 JWKS 端点 https://your-casdoor.com/.well-known/jwks。
  • 检查令牌是否为有效的 JWT,例如在 jwt.io 上查看。

令牌因受众问题被拒绝​

aud 声明必须与您的元数据文档中的 resource 完全一致,包括协议方案且末尾不带斜杠。请检查客户端是否在 resource 参数中发送了相同的值。

令牌过期时间过早或过晚​

同步您服务器的时钟。JWT 的过期时间依赖于它。

Casdoor 仅对用户尚未授予权限的自定义范围请求同意。请检查客户端是否请求了您的范围,并在 Consents 页面上撤销之前的授权以重新测试。

另请参阅​