Add OAuth proxy that allows authentication with social IDPs without DCR support (#1434)

This commit is contained in:
Jeremiah Lowin 2025-08-18 13:39:58 -04:00 committed by GitHub
commit ec015de3b0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 3818 additions and 28 deletions

View file

@ -99,8 +99,9 @@
"icon": "shield-check",
"pages": [
"servers/auth/authentication",
"servers/auth/remote-oauth",
"servers/auth/token-verification",
"servers/auth/remote-oauth",
"servers/auth/oauth-proxy",
"servers/auth/full-oauth-server"
]
},
@ -122,10 +123,7 @@
{
"group": "Essentials",
"icon": "cube",
"pages": [
"clients/client",
"clients/transports"
]
"pages": ["clients/client", "clients/transports"]
},
{
"group": "Core Operations",
@ -151,10 +149,7 @@
{
"group": "Authentication",
"icon": "user-shield",
"pages": [
"clients/auth/oauth",
"clients/auth/bearer"
]
"pages": ["clients/auth/oauth", "clients/auth/bearer"]
}
]
},
@ -163,6 +158,8 @@
"pages": [
"integrations/anthropic",
"integrations/authkit",
"integrations/github",
"integrations/google",
"integrations/chatgpt",
"integrations/claude-code",
"integrations/claude-desktop",
@ -200,17 +197,12 @@
},
{
"anchor": "What's New",
"pages": [
"updates",
"changelog"
]
"pages": ["updates", "changelog"]
},
{
"anchor": "Community",
"icon": "users",
"pages": [
"community/showcase"
]
"pages": ["community/showcase"]
}
]
},

View file

@ -0,0 +1,205 @@
---
title: GitHub OAuth 🤝 FastMCP
sidebarTitle: GitHub OAuth
description: Secure your FastMCP server with GitHub OAuth
icon: github
tag: NEW
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.12.0" />
This guide shows you how to secure your FastMCP server using **GitHub OAuth**. Since GitHub doesn't support Dynamic Client Registration, this integration uses the [**OAuth Proxy**](/servers/auth/oauth-proxy) pattern to bridge GitHub's traditional OAuth with MCP's authentication requirements.
## Configuration
### Prerequisites
Before you begin, you will need:
1. A **[GitHub Account](https://github.com/)** with access to create OAuth Apps
2. Your FastMCP server's URL (can be localhost for development, e.g., `http://localhost:8000`)
### Step 1: Create a GitHub OAuth App
Create an OAuth App in your GitHub settings to get the credentials needed for authentication:
<Steps>
<Step title="Navigate to OAuth Apps">
Go to **Settings → Developer settings → OAuth Apps** in your GitHub account, or visit [github.com/settings/developers](https://github.com/settings/developers).
Click **"New OAuth App"** to create a new application.
</Step>
<Step title="Configure Your OAuth App">
Fill in the application details:
- **Application name**: Choose a name users will recognize (e.g., "My FastMCP Server")
- **Homepage URL**: Your application's homepage or documentation URL
- **Authorization callback URL**: Your server URL + `/oauth/callback` (e.g., `http://localhost:8000/oauth/callback`)
<Warning>
The callback URL must match exactly. The default path is `/oauth/callback`, but you can customize it using the `redirect_path` parameter. For local development, GitHub allows `http://localhost` URLs. For production, you must use HTTPS.
</Warning>
<Tip>
If you want to use a custom callback path (e.g., `/auth/github/callback`), make sure to set the same path in both your GitHub OAuth App settings and the `redirect_path` parameter when configuring the GitHubProvider.
</Tip>
</Step>
<Step title="Save Your Credentials">
After creating the app, you'll see:
- **Client ID**: A public identifier like `Ov23liAbcDefGhiJkLmN`
- **Client Secret**: Click "Generate a new client secret" and save the value securely
<Tip>
Store these credentials securely. Never commit them to version control. Use environment variables or a secrets manager in production.
</Tip>
</Step>
</Steps>
### Step 2: FastMCP Configuration
Create your FastMCP server using the `GitHubProvider`, which handles GitHub's OAuth quirks automatically:
```python server.py
from fastmcp import FastMCP
from fastmcp.server.auth.providers.github import GitHubProvider
# The GitHubProvider handles GitHub's token format and validation
auth_provider = GitHubProvider(
client_id="Ov23liAbcDefGhiJkLmN", # Your GitHub OAuth App Client ID
client_secret="github_pat_...", # Your GitHub OAuth App Client Secret
base_url="http://localhost:8000", # Must match your OAuth App configuration
# redirect_path="/oauth/callback" # Default value, customize if needed
)
mcp = FastMCP(name="GitHub Secured App", auth=auth_provider)
# Add a protected tool to test authentication
@mcp.tool
async def get_user_info() -> dict:
"""Returns information about the authenticated GitHub user."""
from fastmcp.server.dependencies import get_access_token
token = get_access_token()
# The GitHubProvider stores user data in token claims
return {
"github_user": token.claims.get("login"),
"name": token.claims.get("name"),
"email": token.claims.get("email")
}
```
## Testing
### Running the Server
Start your FastMCP server with HTTP transport to enable OAuth flows:
```bash
fastmcp run server.py --transport http --port 8000
```
Your server is now running and protected by GitHub OAuth authentication.
### Testing with a Client
Create a test client that authenticates with your GitHub-protected server:
```python test_client.py
from fastmcp import Client
import asyncio
async def main():
# The client will automatically handle GitHub OAuth
async with Client("http://localhost:8000/mcp/", auth="oauth") as client:
# First-time connection will open GitHub login in your browser
print("✓ Authenticated with GitHub!")
# Test the protected tool
result = await client.call_tool("get_user_info")
print(f"GitHub user: {result['github_user']}")
if __name__ == "__main__":
asyncio.run(main())
```
When you run the client for the first time:
1. Your browser will open to GitHub's authorization page
2. After you authorize the app, you'll be redirected back
3. The client receives the token and can make authenticated requests
<Info>
The client caches tokens locally, so you won't need to re-authenticate for subsequent runs unless the token expires or you explicitly clear the cache.
</Info>
## Environment Variables
For production deployments, use environment variables instead of hardcoding credentials.
<Info>
To use the registered GitHub provider, you must set `FASTMCP_SERVER_AUTH=GITHUB`. Learn more about [registered providers](/servers/auth/authentication#registered-providers).
</Info>
### Provider Selection
<ParamField path="FASTMCP_SERVER_AUTH" default="Not set" required>
Set to `GITHUB` to use the registered GitHubProvider with default configuration.
</ParamField>
### GitHub-Specific Configuration
<Card>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID" required>
Your GitHub OAuth App Client ID (e.g., `Ov23liAbcDefGhiJkLmN`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET" required>
Your GitHub OAuth App Client Secret
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_BASE_URL" default="http://localhost:8000">
Public URL of your FastMCP server for OAuth callbacks
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_REDIRECT_PATH" default="/oauth/callback">
Redirect path configured in your GitHub OAuth App
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES" default='["user"]'>
Comma-separated list of required GitHub scopes (e.g., `user,repo`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_TIMEOUT_SECONDS" default="10">
HTTP request timeout for GitHub API calls
</ParamField>
</Card>
Example `.env` file:
```bash
# Use the registered GitHub provider
FASTMCP_SERVER_AUTH=GITHUB
# GitHub OAuth credentials
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID=Ov23liAbcDefGhiJkLmN
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET=github_pat_...
FASTMCP_SERVER_AUTH_GITHUB_BASE_URL=https://your-server.com
FASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES=user,repo
```
With environment variables set, your server code simplifies to:
```python server.py
from fastmcp import FastMCP
# Authentication is automatically configured from environment
mcp = FastMCP(name="GitHub Secured App")
@mcp.tool
async def list_repos() -> list[str]:
"""List the authenticated user's repositories."""
# Your tool implementation here
pass
```

View file

@ -0,0 +1,215 @@
---
title: Google OAuth 🤝 FastMCP
sidebarTitle: Google OAuth
description: Secure your FastMCP server with Google OAuth
icon: google
tag: NEW
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.12.0" />
This guide shows you how to secure your FastMCP server using **Google OAuth**. Since Google doesn't support Dynamic Client Registration, this integration uses the [**OAuth Proxy**](/servers/auth/oauth-proxy) pattern to bridge Google's traditional OAuth with MCP's authentication requirements.
## Configuration
### Prerequisites
Before you begin, you will need:
1. A **[Google Cloud Account](https://console.cloud.google.com/)** with access to create OAuth 2.0 Client IDs
2. Your FastMCP server's URL (can be localhost for development, e.g., `http://localhost:8000`)
### Step 1: Create a Google OAuth 2.0 Client ID
Create an OAuth 2.0 Client ID in your Google Cloud Console to get the credentials needed for authentication:
<Steps>
<Step title="Navigate to OAuth Consent Screen">
Go to the [Google Cloud Console](https://console.cloud.google.com/apis/credentials) and select your project (or create a new one).
First, configure the OAuth consent screen by navigating to **APIs & Services → OAuth consent screen**. Choose "External" for testing or "Internal" for G Suite organizations.
</Step>
<Step title="Create OAuth 2.0 Client ID">
Navigate to **APIs & Services → Credentials** and click **"+ CREATE CREDENTIALS"** → **"OAuth client ID"**.
Configure your OAuth client:
- **Application type**: Web application
- **Name**: Choose a descriptive name (e.g., "FastMCP Server")
- **Authorized JavaScript origins**: Add your server's base URL (e.g., `http://localhost:8000`)
- **Authorized redirect URIs**: Add your server URL + `/oauth/callback` (e.g., `http://localhost:8000/oauth/callback`)
<Warning>
The redirect URI must match exactly. The default path is `/oauth/callback`, but you can customize it using the `redirect_path` parameter. For local development, Google allows `http://localhost` URLs with various ports. For production, you must use HTTPS.
</Warning>
<Tip>
If you want to use a custom callback path (e.g., `/auth/google/callback`), make sure to set the same path in both your Google OAuth Client settings and the `redirect_path` parameter when configuring the GoogleProvider.
</Tip>
</Step>
<Step title="Save Your Credentials">
After creating the client, you'll receive:
- **Client ID**: A string ending in `.apps.googleusercontent.com`
- **Client Secret**: A string starting with `GOCSPX-`
Download the JSON credentials or copy these values securely.
<Tip>
Store these credentials securely. Never commit them to version control. Use environment variables or a secrets manager in production.
</Tip>
</Step>
</Steps>
### Step 2: FastMCP Configuration
Create your FastMCP server using the `GoogleProvider`, which handles Google's OAuth flow automatically:
```python server.py
from fastmcp import FastMCP
from fastmcp.server.auth.providers.google import GoogleProvider
# The GoogleProvider handles Google's token format and validation
auth_provider = GoogleProvider(
client_id="123456789.apps.googleusercontent.com", # Your Google OAuth Client ID
client_secret="GOCSPX-abc123...", # Your Google OAuth Client Secret
base_url="http://localhost:8000", # Must match your OAuth configuration
required_scopes=["openid", "email", "profile"], # Request user information
# redirect_path="/oauth/callback" # Default value, customize if needed
)
mcp = FastMCP(name="Google Secured App", auth=auth_provider)
# Add a protected tool to test authentication
@mcp.tool
async def get_user_info() -> dict:
"""Returns information about the authenticated Google user."""
from fastmcp.server.dependencies import get_access_token
token = get_access_token()
# The GoogleProvider stores user data in token claims
return {
"google_id": token.claims.get("sub"),
"email": token.claims.get("email"),
"name": token.claims.get("name"),
"picture": token.claims.get("picture"),
"locale": token.claims.get("locale")
}
```
## Testing
### Running the Server
Start your FastMCP server with HTTP transport to enable OAuth flows:
```bash
fastmcp run server.py --transport http --port 8000
```
Your server is now running and protected by Google OAuth authentication.
### Testing with a Client
Create a test client that authenticates with your Google-protected server:
```python test_client.py
from fastmcp import Client
import asyncio
async def main():
# The client will automatically handle Google OAuth
async with Client("http://localhost:8000/mcp/", auth="oauth") as client:
# First-time connection will open Google login in your browser
print("✓ Authenticated with Google!")
# Test the protected tool
result = await client.call_tool("get_user_info")
print(f"Google user: {result['email']}")
print(f"Name: {result['name']}")
if __name__ == "__main__":
asyncio.run(main())
```
When you run the client for the first time:
1. Your browser will open to Google's authorization page
2. Sign in with your Google account and grant the requested permissions
3. After authorization, you'll be redirected back
4. The client receives the token and can make authenticated requests
<Info>
The client caches tokens locally, so you won't need to re-authenticate for subsequent runs unless the token expires or you explicitly clear the cache.
</Info>
## Environment Variables
For production deployments, use environment variables instead of hardcoding credentials.
<Info>
To use the registered Google provider, you must set `FASTMCP_SERVER_AUTH=GOOGLE`. Learn more about [registered providers](/servers/auth/authentication#registered-providers).
</Info>
### Provider Selection
<ParamField path="FASTMCP_SERVER_AUTH" default="Not set" required>
Set to `GOOGLE` to use the registered GoogleProvider with default configuration.
</ParamField>
### Google-Specific Configuration
<Card>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID" required>
Your Google OAuth 2.0 Client ID (e.g., `123456789.apps.googleusercontent.com`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET" required>
Your Google OAuth 2.0 Client Secret (e.g., `GOCSPX-abc123...`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_BASE_URL" default="http://localhost:8000">
Public URL of your FastMCP server for OAuth callbacks
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_REDIRECT_PATH" default="/oauth/callback">
Redirect path configured in your Google OAuth Client
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_REQUIRED_SCOPES" default="[]">
Comma-separated list of required Google scopes (e.g., `openid`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_TIMEOUT_SECONDS" default="10">
HTTP request timeout for Google API calls
</ParamField>
</Card>
Example `.env` file:
```bash
# Use the registered Google provider
FASTMCP_SERVER_AUTH=GOOGLE
# Google OAuth credentials
FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID=123456789.apps.googleusercontent.com
FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET=GOCSPX-abc123...
FASTMCP_SERVER_AUTH_GOOGLE_BASE_URL=https://your-server.com
FASTMCP_SERVER_AUTH_GOOGLE_REQUIRED_SCOPES=openid,email,profile
```
With environment variables set, your server code simplifies to:
```python server.py
from fastmcp import FastMCP
# Authentication is automatically configured from environment
mcp = FastMCP(name="Google Secured App")
@mcp.tool
async def protected_tool(query: str) -> str:
"""A tool that requires Google authentication to access."""
# Your tool implementation here
return f"Processing authenticated request: {query}"
```

View file

@ -34,7 +34,7 @@ Traditional web authentication assumes a human user with a browser who can inter
These challenges mean that not all authentication approaches work well with MCP. The patterns that do work fall into three categories based on the level of authentication responsibility your server assumes.
## Understanding Authentication Responsibility
## Authentication Responsibility
Authentication responsibility exists on a spectrum. Your MCP server can validate tokens created elsewhere, coordinate with external identity providers, or handle the complete authentication lifecycle internally. Each approach involves different trade-offs between simplicity, security, and control.
@ -66,9 +66,9 @@ Full OAuth implementation means building user interfaces for login and consent,
This pattern makes sense only when you need complete control over the authentication process, operate in air-gapped environments, or have specialized requirements that external providers cannot meet.
## FastMCP Implementation
## FastMCP Authentication Providers
FastMCP translates these authentication responsibility levels into three concrete classes that handle the complexities of MCP protocol integration.
FastMCP translates these authentication responsibility levels into a variety of concrete classes that handle the complexities of MCP protocol integration. You can build on these classes to handle the complexities of MCP protocol integration.
### TokenVerifier
@ -97,11 +97,13 @@ This example configures token validation against a JWT issuer. The `JWTVerifier`
### RemoteAuthProvider
`RemoteAuthProvider` combines token validation with OAuth discovery metadata, enabling MCP clients to automatically discover and authenticate with external identity providers.
`RemoteAuthProvider` enables authentication with identity providers that **support Dynamic Client Registration (DCR)**, such as WorkOS AuthKit. With DCR, MCP clients can automatically register themselves with the identity provider and obtain credentials without any manual configuration.
This class extends `TokenVerifier` functionality by adding OAuth 2.0 protected resource endpoints that advertise your authentication requirements. MCP clients can examine these endpoints to understand which identity providers you trust and how to obtain valid tokens.
This class combines token validation with OAuth discovery metadata. It extends `TokenVerifier` functionality by adding OAuth 2.0 protected resource endpoints that advertise your authentication requirements. MCP clients examine these endpoints to understand which identity providers you trust and how to obtain valid tokens.
The implementation handles the OAuth metadata generation required by the MCP specification while delegating actual token validation to an underlying `TokenVerifier`. This separation allows you to use different token validation strategies while maintaining consistent OAuth discovery behavior.
The key requirement is that your identity provider must support DCR - the ability for clients to dynamically register and obtain credentials. This is what enables the seamless, automated authentication flow that MCP requires.
For example, the built-in `AuthKitProvider` uses WorkOS AuthKit, which fully supports DCR:
```python
from fastmcp import FastMCP
@ -117,10 +119,41 @@ mcp = FastMCP(name="Enterprise Server", auth=auth)
This example uses WorkOS AuthKit as the external identity provider. The `AuthKitProvider` automatically configures token validation against WorkOS and provides the OAuth metadata that MCP clients need for automatic authentication.
`RemoteAuthProvider` excels for production applications that need professional identity management without implementation complexity.
`RemoteAuthProvider` is ideal for production applications when your identity provider supports Dynamic Client Registration (DCR). This enables fully automated authentication without manual client configuration.
→ **Complete guide**: [Remote OAuth](/servers/auth/remote-oauth)
### OAuthProxy
<VersionBadge version="2.12.0" />
`OAuthProxy` enables authentication with OAuth providers that **don't support Dynamic Client Registration (DCR)**, such as GitHub, Google, Azure, and most traditional enterprise identity systems.
When identity providers require manual app registration and fixed credentials, `OAuthProxy` bridges the gap. It presents a DCR-compliant interface to MCP clients (accepting any registration request) while using your pre-registered credentials with the upstream provider. The proxy handles the complexity of callback forwarding, enabling dynamic client callbacks to work with providers that require fixed redirect URIs.
This class solves the fundamental incompatibility between MCP's expectation of dynamic registration and traditional OAuth providers' requirement for manual app registration.
For example, the built-in `GitHubProvider` extends `OAuthProxy` to work with GitHub's OAuth system:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.github import GitHubProvider
auth = GitHubProvider(
client_id="Ov23li...", # Your GitHub OAuth App ID
client_secret="abc123...", # Your GitHub OAuth App Secret
base_url="https://your-server.com"
)
mcp = FastMCP(name="GitHub-Protected Server", auth=auth)
```
This example uses the GitHub provider, which extends `OAuthProxy` with GitHub-specific token validation. The proxy handles the complete OAuth flow while making GitHub's non-DCR authentication work seamlessly with MCP clients.
`OAuthProxy` is essential when integrating with OAuth providers that don't support DCR. This includes most established providers like GitHub, Google, and Azure, which require manual app registration through their developer consoles.
→ **Complete guide**: [OAuth Proxy](/servers/auth/oauth-proxy)
### OAuthProvider
`OAuthProvider` implements a complete OAuth 2.0 authorization server within your MCP server. This class handles the full authentication lifecycle from user credential verification to token management.
@ -162,6 +195,37 @@ Environment-based configuration separates authentication settings from applicati
FastMCP automatically detects authentication configuration from environment variables when no explicit `auth` parameter is provided. The configuration system supports all authentication providers and their various options.
#### Registered Providers
FastMCP includes pre-configured providers for popular OAuth services that can be activated with a single environment variable:
<ParamField path="FASTMCP_SERVER_AUTH" type="string">
The authentication provider to use. Supported values:
- `GITHUB` - GitHub OAuth (requires additional GitHub-specific env vars)
- `GOOGLE` - Google OAuth (requires additional Google-specific env vars)
- `JWT` - JWT token verification
- `WORKOS` - WorkOS AuthKit
- Custom provider class names
</ParamField>
When using registered providers like GitHub or Google, you'll need to set provider-specific environment variables:
```bash
# GitHub OAuth
export FASTMCP_SERVER_AUTH=GITHUB
export FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID="Ov23li..."
export FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET="github_pat_..."
# Google OAuth
export FASTMCP_SERVER_AUTH=GOOGLE
export FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID="123456.apps.googleusercontent.com"
export FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET="GOCSPX-..."
```
#### Custom Provider Configuration
For providers that aren't pre-registered, specify the provider class and its configuration:
```bash
export FASTMCP_SERVER_AUTH=JWT
export FASTMCP_SERVER_AUTH_JWT_JWKS_URI="https://auth.example.com/jwks"
@ -184,7 +248,9 @@ This approach simplifies deployment pipelines and follows twelve-factor app prin
The authentication approach you choose depends on your existing infrastructure, security requirements, and operational constraints.
**For most production applications, external identity providers offer the best balance of security, features, and simplicity.** This approach provides enterprise-grade authentication without implementation complexity and scales well as your application grows. The main trade-off is requiring users to sign up with your chosen identity provider, but this also brings benefits like professional user management, security monitoring, and compliance features.
**For OAuth providers without DCR support (GitHub, Google, Azure, most enterprise systems), use OAuth Proxy.** These providers require manual app registration through their developer consoles. OAuth Proxy bridges the gap by presenting a DCR-compliant interface to MCP clients while using your fixed credentials with the provider. The proxy's callback forwarding pattern enables dynamic client ports to work with providers that require fixed redirect URIs.
**For identity providers with DCR support (WorkOS AuthKit, modern auth platforms), use RemoteAuthProvider.** These providers allow clients to dynamically register and obtain credentials without manual configuration. This enables the fully automated authentication flow that MCP is designed for, providing the best user experience and simplest implementation.
**Token validation works well when you already have authentication infrastructure that issues structured tokens.** If your organization already uses JWT-based systems, API gateways, or enterprise SSO that can generate tokens, this approach integrates seamlessly while keeping your MCP server focused on its core functionality. The simplicity comes from leveraging existing investment in authentication infrastructure.

View file

@ -0,0 +1,300 @@
---
title: OAuth Proxy
sidebarTitle: OAuth Proxy
description: Enable authentication with OAuth providers that don't support Dynamic Client Registration.
icon: share
tag: NEW
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.12.0" />
OAuth Proxy enables your FastMCP server to authenticate with OAuth providers that **don't support Dynamic Client Registration (DCR)**. This includes virtually all traditional OAuth providers: GitHub, Google, Azure, Facebook, Discord, and most enterprise identity systems.
While MCP clients expect to dynamically register and obtain credentials, these providers require manual app registration through their developer consoles. OAuth Proxy bridges this gap by presenting a DCR-compliant interface to MCP clients while using your pre-registered credentials with the upstream provider.
<Tip>
**When to use OAuth Proxy vs RemoteAuthProvider:**
- **OAuth Proxy**: For providers WITHOUT Dynamic Client Registration (GitHub, Google, Azure, etc.)
- **RemoteAuthProvider**: For providers WITH Dynamic Client Registration (WorkOS AuthKit, etc.)
OAuth Proxy makes traditional OAuth providers work seamlessly with MCP's automated authentication flow.
</Tip>
## DCR vs Non-DCR Providers
The key distinction in MCP authentication is whether your OAuth provider supports **Dynamic Client Registration (DCR)**:
- **Providers WITH DCR** (WorkOS, some OIDC providers): Use [`RemoteAuthProvider`](/servers/auth/remote-oauth)
- Clients can register themselves automatically
- No manual app registration needed
- True dynamic authentication flow
- **Providers WITHOUT DCR** (GitHub, Google, Azure, Discord, etc.): Use `OAuthProxy` (this guide)
- Requires manual app registration in provider's console
- You obtain fixed client ID and secret
- OAuth Proxy bridges the gap for MCP compatibility
OAuth Proxy makes non-DCR providers work seamlessly with MCP by implementing a local DCR interface that always returns your pre-registered credentials.
## Understanding the DCR Gap
**Dynamic Client Registration (DCR)** allows OAuth clients to automatically register themselves with an authorization server and obtain credentials without manual intervention. The MCP specification is designed around this capability, expecting clients to register dynamically.
However, most OAuth providers don't support DCR:
| Provider Type | DCR Support | Registration Method | Examples |
|--------------|-------------|--------------------|-----------|
| Modern Auth Platforms | ✅ Yes | Automatic via API | WorkOS AuthKit, Some OIDC providers |
| Traditional OAuth | ❌ No | Manual via console | GitHub, Google, Azure, Discord, Facebook |
| Enterprise SSO | ❌ No | IT Administrator | Okta, AD FS, PingIdentity |
Providers without DCR require you to:
- Manually register applications through their developer console
- Obtain fixed client IDs and secrets that never change
- Pre-configure specific redirect URIs
- Manage credentials through their web interface
This creates a fundamental incompatibility: MCP clients expect to call a registration endpoint and receive credentials, but traditional providers only work with pre-registered apps. OAuth Proxy solves this by accepting any client registration request and returning your fixed upstream credentials.
## How OAuth Proxy Works
The OAuth Proxy implements an intelligent callback forwarding pattern that solves both the DCR problem and the redirect URI mismatch issue:
```mermaid
sequenceDiagram
participant Client as MCP Client<br/>(localhost:random)
participant Proxy as FastMCP OAuth Proxy<br/>(server:8000)
participant Provider as OAuth Provider<br/>(GitHub, etc.)
Note over Client, Proxy: Dynamic Registration (Local)
Client->>Proxy: 1. POST /register<br/>redirect_uri: localhost:54321/callback
Proxy-->>Client: 2. Returns fixed upstream credentials
Note over Client, Proxy: Authorization with Callback Forwarding
Client->>Proxy: 3. GET /authorize<br/>redirect_uri=localhost:54321/callback
Note over Proxy: Store transaction with client callback
Proxy->>Provider: 4. Redirect to provider<br/>redirect_uri=server:8000/oauth/callback
Note over Provider, Proxy: Provider Callback
Provider->>Proxy: 5. GET /oauth/callback<br/>with authorization code
Proxy->>Provider: 6. Exchange code for tokens
Provider-->>Proxy: 7. Access & refresh tokens
Note over Proxy, Client: Client Callback Forwarding
Proxy->>Client: 8. Redirect to localhost:54321/callback<br/>with new authorization code
Note over Client, Proxy: Token Exchange
Client->>Proxy: 9. POST /token with code
Proxy-->>Client: 10. Returns stored provider tokens
```
### The Callback Forwarding Pattern
OAuth Proxy implements an innovative callback forwarding pattern that solves the redirect URI mismatch problem:
**The Challenge:**
- MCP clients listen on random localhost ports (e.g., `http://localhost:54321/callback`)
- Each client session uses a different port
- OAuth providers only accept pre-registered, fixed redirect URIs
- Registering every possible localhost port is impossible
**The Solution:**
The proxy acts as an intermediary callback handler:
1. **Dynamic Registration**: Client provides its localhost callback URL during registration
2. **Transaction Tracking**: Proxy stores the client's callback URL with a transaction ID
3. **Fixed Provider Callback**: Proxy uses its own fixed callback URL with the provider
4. **Server-Side Token Exchange**: Proxy receives the provider's callback and exchanges the authorization code for tokens
5. **Client Forwarding**: Proxy redirects to the client's original localhost callback with a new authorization code
6. **Token Delivery**: Client exchanges this new code with the proxy to receive the provider's tokens
This pattern maintains full OAuth 2.1 security (including PKCE) while enabling dynamic client ports to work with fixed provider callbacks. The client never knows it's talking to a proxy - it experiences a standard DCR flow.
## Basic Implementation
The `OAuthProxy` class provides the complete proxy implementation:
<Card icon="code" title="OAuthProxy Constructor Parameters">
<ParamField body="upstream_authorization_endpoint" type="str" required>
URL of your OAuth provider's authorization endpoint (e.g., `https://github.com/login/oauth/authorize`)
</ParamField>
<ParamField body="upstream_token_endpoint" type="str" required>
URL of your OAuth provider's token endpoint (e.g., `https://github.com/login/oauth/access_token`)
</ParamField>
<ParamField body="upstream_client_id" type="str" required>
Client ID from your registered OAuth application
</ParamField>
<ParamField body="upstream_client_secret" type="str" required>
Client secret from your registered OAuth application
</ParamField>
<ParamField body="token_verifier" type="TokenVerifier" required>
A [`TokenVerifier`](/servers/auth/token-verification) instance to validate the provider's tokens
</ParamField>
<ParamField body="base_url" type="AnyHttpUrl | str" required>
Public URL of your FastMCP server (e.g., `https://your-server.com`)
</ParamField>
<ParamField body="redirect_path" type="str" default="/oauth/callback">
Path for OAuth callbacks. Must match the redirect URI configured in your OAuth application
</ParamField>
<ParamField body="upstream_revocation_endpoint" type="str | None">
Optional URL of provider's token revocation endpoint
</ParamField>
<ParamField body="issuer_url" type="AnyHttpUrl | str | None">
Issuer URL for OAuth metadata (defaults to base_url)
</ParamField>
<ParamField body="service_documentation_url" type="AnyHttpUrl | str | None">
Optional URL to your service documentation
</ParamField>
<ParamField body="resource_server_url" type="AnyHttpUrl | str | None">
Resource server URL (defaults to base_url)
</ParamField>
</Card>
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.proxy import OAuthProxy
from fastmcp.server.auth.providers.jwt import JWTVerifier
# Configure token validation for your provider
token_verifier = JWTVerifier(
jwks_uri="https://your-provider.com/.well-known/jwks.json",
issuer="https://your-provider.com",
audience="your-app-id"
)
# Create the OAuth proxy (accepts strings for URLs)
auth = OAuthProxy(
# Upstream provider endpoints
upstream_authorization_endpoint="https://your-provider.com/oauth/authorize",
upstream_token_endpoint="https://your-provider.com/oauth/token",
# Your registered app credentials
upstream_client_id="your-registered-client-id",
upstream_client_secret="your-registered-client-secret",
# Token validation
token_verifier=token_verifier,
# Your FastMCP server URL (string automatically converted to AnyHttpUrl)
base_url="https://your-server.com",
# Optional: customize callback path (defaults to "/oauth/callback")
redirect_path="/oauth/callback"
)
mcp = FastMCP(name="My Server", auth=auth)
```
### OAuth Provider Configuration
When registering your application with your OAuth provider, configure the redirect/callback URL as:
```
https://your-server.com/oauth/callback
```
For local development with providers that support it (like GitHub):
```
http://localhost:8000/oauth/callback
```
The proxy automatically:
- Implements DCR by returning your fixed credentials to any client that registers
- Handles callback forwarding between dynamic client callbacks and your fixed provider callback
- Exchanges authorization codes server-side for enhanced security
- Validates tokens using your provider's public keys or API
- Maintains PKCE security throughout the flow
## Client Compatibility
<Tip>
The OAuth Proxy's callback forwarding enables **any MCP client** to authenticate with **any OAuth provider**, regardless of redirect URI restrictions. Clients can use dynamic localhost ports while providers see their expected fixed callbacks.
</Tip>
This breakthrough means that MCP clients no longer need to worry about registering specific callback URLs with OAuth providers. The proxy handles the complexity of bridging dynamic client callbacks with the fixed URLs that providers require. The entire flow maintains OAuth 2.1 and PKCE (RFC-7636) compliance for security.
## Token Verification Strategies
Different OAuth providers use different token formats, requiring appropriate verification strategies:
### Provider Token Types
| Provider | Token Type | Verification Method | Built-in Support |
|----------|-----------|--------------------|-----------------|
| GitHub | Opaque | API validation (`/user` endpoint) | ✅ `GitHubProvider` |
| Google | JWT | JWKS signature verification | ✅ `GoogleProvider` |
| Azure AD | JWT | JWKS signature verification | Configure `JWTVerifier` |
| Discord | Opaque | API validation | ✅ `DiscordOAuthProxyProvider` |
| Custom | Varies | Implement `TokenVerifier` | Extend base class |
### Using Built-in Providers
FastMCP includes pre-configured providers that handle token verification automatically:
```python
from fastmcp.server.auth.providers.github import GitHubProvider
# GitHub provider with automatic API-based token validation
auth = GitHubProvider(
client_id="your-github-client-id",
client_secret="your-github-client-secret",
base_url="https://your-server.com"
)
```
### Custom Token Verification
For providers without built-in support, implement a [`TokenVerifier`](/servers/auth/token-verification):
- **JWT tokens**: Use `JWTVerifier` with the provider's JWKS endpoint
- **Opaque tokens**: Extend `TokenVerifier` to validate via the provider's API
- **Hybrid approaches**: Combine multiple verification methods as needed
## Environment Configuration
OAuth Proxy supports environment-based configuration for production deployments:
```bash
# Provider selection
export FASTMCP_SERVER_AUTH=OAUTH_PROXY
# OAuth endpoints
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_UPSTREAM_AUTHORIZATION_ENDPOINT="https://github.com/login/oauth/authorize"
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_UPSTREAM_TOKEN_ENDPOINT="https://github.com/login/oauth/access_token"
# Credentials (use secrets management in production)
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_UPSTREAM_CLIENT_ID="Ov23li..."
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_UPSTREAM_CLIENT_SECRET="abc123..."
# Token validation
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_TOKEN_VERIFIER="JWT"
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_JWKS_URI="https://provider.com/.well-known/jwks.json"
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_ISSUER="https://provider.com"
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_AUDIENCE="your-app-id"
# Server URL
export FASTMCP_SERVER_AUTH_OAUTH_PROXY_BASE_URL="https://your-server.com"
```
With environment variables configured, your code becomes:
```python
from fastmcp import FastMCP
# Authentication automatically configured from environment
mcp = FastMCP(name="My Server")
```

View file

@ -10,12 +10,30 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.11.0" />
Remote OAuth integration allows your FastMCP server to leverage external identity providers while maintaining the automated authentication flows that MCP clients require. This approach provides enterprise-grade authentication features without the complexity of implementing them yourself, making it the recommended pattern for most production applications.
Remote OAuth integration allows your FastMCP server to leverage external identity providers that **support Dynamic Client Registration (DCR)**. With DCR, MCP clients can automatically register themselves with the identity provider and obtain credentials without any manual configuration. This provides enterprise-grade authentication with fully automated flows, making it ideal for production applications with modern identity providers.
<Tip>
Remote OAuth requires identity providers that support **Dynamic Client Registration (DCR)**. This enables MCP clients to automatically register and authenticate without manual configuration steps.
**When to use RemoteAuthProvider vs OAuth Proxy:**
- **RemoteAuthProvider**: For providers WITH Dynamic Client Registration (WorkOS AuthKit, modern OIDC providers)
- **OAuth Proxy**: For providers WITHOUT Dynamic Client Registration (GitHub, Google, Azure, Discord, etc.)
RemoteAuthProvider requires DCR support for fully automated client registration and authentication.
</Tip>
## DCR-Enabled Providers
RemoteAuthProvider works with identity providers that support **Dynamic Client Registration (DCR)** - a critical capability that enables automated authentication flows:
| Feature | DCR Providers (RemoteAuth) | Non-DCR Providers (OAuth Proxy) |
|---------|---------------------------|--------------------------------|
| **Client Registration** | Automatic via API | Manual in provider console |
| **Credentials** | Dynamic per client | Fixed app credentials |
| **Configuration** | Zero client config | Pre-shared credentials |
| **Examples** | WorkOS AuthKit, modern OIDC | GitHub, Google, Azure |
| **FastMCP Class** | `RemoteAuthProvider` | [`OAuthProxy`](/servers/auth/oauth-proxy) |
If your provider doesn't support DCR (most traditional OAuth providers), you'll need to use [`OAuth Proxy`](/servers/auth/oauth-proxy) instead, which bridges the gap between MCP's DCR expectations and fixed OAuth credentials.
## The Remote OAuth Challenge
Traditional OAuth flows assume human users with web browsers who can interact with login forms, consent screens, and redirects. MCP clients operate differently - they're often automated systems that need to authenticate programmatically without human intervention.