使用Spring授权服务器和GitHub OAuth2来保护模型上下文协议(MCP)服务器的演示。用户通过GitHub进行身份验证,接收一个JWT令牌,并使用该令牌调用受保护的MCP工具。
基于Daniel Garnier-Moiroux的文章: https://spring.io/blog/2025/09/30/spring-ai-mcp-server-security

┌─────────────┐
│ GitHub │ (身份提供者)
└──────┬──────┘
│
▼
┌────────────────────────┐
│ 授权服务器 │ (端口9000)
│ - GitHub OAuth登录 │
│ - 发放JWT令牌 │
└──────┬─────────────────┘
│
▼
┌─────────────┐ Authorization: Bearer <JWT> ┌──────────────┐
│ MCP客户端 │──────────────────────────────► │ MCP服务器 │ (端口8080)
└─────────────┘ │ - 2个工具 │
└──────────────┘
mcps/
├── pom.xml # 父POM
├── mvnw # Maven包装器
│
├── authorization-server/ # 端口9000
│ └── src/main/java/dev/danvega/authserver/
│ ├── AuthServerApplication.java # 主应用程序
│ ├── SecurityConfig.java # OAuth2 + GitHub登录
│ └── application.yml # 配置
│
└── mcp-server/ # 端口8080
└── src/main/java/dev/danvega/mcps/
├── Application.java # 主应用程序
├── McpServerSecurityConfig.java # JWT验证
└── McpToolsService.java # MCP工具(echo, getCurrentUser)
http://localhost:9000http://localhost:9000/login/oauth2/code/githubexport GITHUB_CLIENT_ID="your-github-client-id"
export GITHUB_CLIENT_SECRET="your-github-client-secret"
# 构建两个模块
./mvnw clean install
# 终端1:启动授权服务器(必须先启动!)
./mvnw spring-boot:run -pl authorization-server
# 终端2:启动MCP服务器
./mvnw spring-boot:run -pl mcp-server
授权服务器在端口9000上运行,MCP服务器在端口8080上运行。



MCP Inspector工具提供了一种简单的方式来测试完整的OAuth2流程并与您的受保护MCP服务器交互。
1. echo - 回显带有时间戳的消息
{"message": "Hello"}
2. getCurrentUser - 获取已认证用户的详细信息
{}
# 授权服务器元数据
curl http://localhost:9000/.well-known/oauth-authorization-server
# JWKS(用于JWT验证的公钥)
curl http://localhost:9000/oauth2/jwks
MCP客户端预注册了以下凭据:
mcp-serversecretopenid, profile, email, mcp.server, mcp.tools令牌的有效期配置在authorization-server/src/main/resources/application.yml中:
401未授权?
GitHub OAuth不起作用?
http://localhost:9000/login/oauth2/code/githubGITHUB_CLIENT_ID和GITHUB_CLIENT_SECRET是否已设置