OAuth认证服务

基于Firestore的OAuth认证服务,提供客户端注册、令牌管理和用户会话数据存储功能,适用于需要安全认证的分布式系统。

  • by redfive410
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 redfive410/mcp-oauth-demo

使用说明

# Terminal 1 - Run auth server
cd auth-server
uv run mcp-simple-auth-as --port=9000

# Terminal 2 - Run resource server
cd mcp-server
uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000  --transport=streamable-http --oauth-strict

# Terminal 3 - Local tests
curl http://localhost:9000/.well-known/oauth-authorization-server | jq

# Terminal 3 - Run MCP Inspector
npx @modelcontextprotocol/inspector
  1. 打开OAuth设置以配置访问令牌
  2. 使用Quick Oauth Flow获取访问令牌
  3. 登录演示身份登录网页
  4. 保存访问令牌
  5. 使用访问令牌作为承载令牌与MCP服务器进行身份验证
  6. 连接到MCP服务器

========

cd auth-server
./deploy.sh
# Run resource server using remote auth server

uv run mcp-simple-auth-rs --port=8001 --auth-server=https://mcp-oauth-auth-server-323998774564.us-west1.run.app  --transport=streamable-http --oauth-strict
curl http://localhost:8001/.well-known/oauth-protected-resource/mcp | jq

curl -X POST https://mcp-oauth-auth-server-323998774564.us-west1.run.app/register \
      -H "Content-Type: application/json" \
      -d '{
        "client_name": "My MCP Client",
        "redirect_uris": ["http://localhost:3000/callback"],
        "grant_types": ["authorization_code", "refresh_token"],
        "response_types": ["code"],
        "scope": "user"
      }'

OAuthClient库构建授权URL。(例如:https://mcp-oauth-auth-server-4vohcegqpq-uw.a.run.app/authorize?response_type=code&client_id=25bfad56-c6db-400f-acff-7d39f5b1f697&重定向_ uri=http%3A%2F%2localhost%3A3030%2回调和状态=CQyV5QwPWLk_KT3SBugeiRkYWXlome-RtJ44hJSyC34&code_challenge=JCnljrfkS0wdOHwUicDJ-Sgf5heVaZgbBkQhE-GbQek&code_chalenge _方法=S256&资源=http%3A%2F%2FLT%3A8001&范围=用户)

授权码被交换为Bearer令牌。

承载令牌作为Auth的标头传递给MCP服务器。

==========

Firestore持久性

OAuth授权服务器现在使用 Firestore 对于持久存储,解决CloudRun实例超时问题。

Firestore中存储的内容

所有OAuth状态在CloudRun重启后仍然存在:

  • OAuth客户端(DCR注册)→ oauth_clients 收集
  • 访问令牌→ oauth_tokens 收集
  • 授权代码→ auth_codes 收集
  • OAuth流状态→ oauth_state 收集
  • 用户会话数据→ user_data 收集

益处

✅ 无状态损失 -令牌在CloudRun实例重启后仍然有效 ✅ 无服务器友好 -没有连接池问题 ✅ 自动缩放 -Firestore可根据您的流量进行扩展 ✅ 快速 -令牌自检的延迟为50-150ms ✅ 成本效益高 -每次使用付费(典型使用约3美元/月)

部署

这 deploy.sh 脚本自动执行:

  1. 启用Firestore API
  2. 创建Firestore数据库(本机模式)
  3. 使用配置CloudRun GCP_PROJECT_ID 环境变量
  4. 授予自动Firestore权限
cd auth-server
./deploy.sh

新端点

手动清理过期数据:

curl -X POST https://your-auth-server.run.app/cleanup

健康检查:

curl https://your-auth-server.run.app/health

文档

看 身份验证服务器/FIRESTORE_SETUP.md 用于:

  • 建筑细部
  • Firestore集合架构
  • 本地开发设置(带模拟器)
  • 监测和维护
  • 成本优化
  • 安全注意事项
  • 故障排除指南

迁移说明

无需数据迁移!首次部署时:

  • Firestore收藏开始为空
  • 现有客户必须通过以下方式重新注册 /register
  • 用户必须重新验证才能获得新令牌

这与CloudRun实例重新启动时的先前行为相匹配。