mcp-oauth2-羟基
一个兼容OAuth 2.1的授权服务器和反向代理,旨在为普通用户添加身份验证 模型上下文协议(MCP) HTTP服务器,上游没有变化。
它位于MCP服务器的前面,处理所有OAuth流,在每个请求上验证Bearer令牌,并将经过身份验证的流量转发到上游。
特性
- 授权码流 使用PKC(S256)——由Claude等MCP客户端使用
- 客户端凭据流 --机器对机器访问
- 基于浏览器的登录表单,带有bcrypt密码验证
- JWT访问令牌(HS256)
iss,aud,sub,exp索赔 - 自动发现端点(RFC 8414+RFC 9728)
- 上游MCP HTTP服务器的透明反向代理
快速开始
git clone https://github.com/clems4ever/mcp-oauth2-proxy
cd mcp-oauth2-proxy
go build -o mcp-oauth2-proxy .
./mcp-oauth2-proxy --config example-config.yaml或者使用Docker:
docker run --rm \
-p 8080:8080 \
-v $PWD/example-config.yaml:/config.yaml \
ghcr.io/clems4ever/mcp-oauth2-proxy --config /config.yaml配置
server:
port: 8080
issuer: "https://auth.example.com" # public base URL — must match what clients see
jwt_secret: "change-me-in-production"
token_ttl: 3600 # access token lifetime, seconds
auth_code_ttl: 300 # authorization code lifetime, seconds
upstream_url: "http://localhost:9090" # MCP HTTP server to proxy authenticated requests to
# Human users for the authorization code flow.
# Passwords are bcrypt hashes — generate with: htpasswd -bnBC 10 ""
| tr -d ':\n'
users:
- username: alice
password: "$2a$10$..."
# Single OAuth2 application (used for both flows).
application:
client_id: "service-client-id"
client_secret: "service-client-secret"
allowed_scopes:
- read
- write
redirect_uris:
- "https://claude.ai/api/mcp/auth_callback"默认配置路径: ~/.mcp-oauth2.yaml.用覆盖 --config.
端点
| 方法 | 路径 | 描述 |
|---|---|---|
GET | /.well-known/oauth-authorization-server | 授权服务器元数据(RFC 8414) |
GET | /.well-known/oauth-protected-resource | 受保护的资源元数据(RFC 9728) |
GET/POST | /oauth2/authorize | 授权端点--显示登录表单,发出身份验证码 |
POST | /oauth2/token | 令牌端点-- authorization_code 和 client_credentials 赠款 |
* | / | 反向代理到 upstream_url (需要有效的Bearer令牌) |
令牌端点
客户端凭据
curl -X POST http://localhost:8080/oauth2/token \
-u service-client-id:service-client-secret \
-d "grant_type=client_credentials&scope=read"授权码(PKCE)
授权码流由MCP客户端启动。代理显示登录表单,用户进行身份验证,并向注册者返回授权码 redirect_uri。然后将代码交换为令牌:
curl -X POST http://localhost:8080/oauth2/token \
-u service-client-id:service-client-secret \
-d "grant_type=authorization_code&code=&redirect_uri=&code_verifier="回应
{
"access_token": "eyJhbGci...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "read write"
}旗帜
| 标志 | 默认值 | 描述 |
|---|---|---|
--config | ~/.mcp-oauth2.yaml | 配置文件的路径 |
安全说明
- PKC与
S256是所有授权代码流所必需的(OAuth 2.1) - 用户密码必须存储为bcrypt哈希值
- 设置强随机
jwt_secret生产中 - 这
issuer值取自config--requestHost标头永远不受信任
