This guide provides comprehensive instructions for setting up OAuth 2.1 authentication in your MCP server, including integration examples for popular OAuth providers.
- Introduction
- Quick Start
- Token Validation Strategies
- Provider Integration
- Advanced Configuration
- Security Considerations
- Troubleshooting
- Migration Guide
OAuth 2.1 authentication in MCP (Model Context Protocol) provides secure, standardized authorization for your MCP servers. The MCP specification (2025-06-18) mandates OAuth 2.1 with PKCE support for production deployments.
| Authentication Method | Use Case |
|---|---|
| OAuth 2.1 | Production deployments, enterprise environments, multi-tenant systems, services requiring user-level authorization |
| JWT | Internal services, simpler authorization needs, when you control token issuance |
| API Key | Development, testing, simple single-tenant deployments, internal tools |
- ✅ Standardized: Industry-standard OAuth 2.1 protocol
- ✅ Secure: PKCE support, token validation, audience verification
- ✅ Scalable: Works with any RFC-compliant authorization server
- ✅ Flexible: Supports both JWT and introspection validation
- ✅ Discoverable: Automatic metadata endpoint (RFC 9728)
Here's the simplest OAuth configuration to get started:
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: ["https://auth.example.com"],
resource: "https://mcp.example.com",
validation: {
type: 'jwt',
jwksUri: "https://auth.example.com/.well-known/jwks.json",
audience: "https://mcp.example.com",
issuer: "https://auth.example.com"
}
})
}
}
}
});
await server.start();
console.log("MCP Server with OAuth running on http://localhost:8080");- Check metadata endpoint:
curl http://localhost:8080/.well-known/oauth-protected-resourceExpected response:
{
"resource": "https://mcp.example.com",
"authorization_servers": ["https://auth.example.com"]
}- Test without token (should fail):
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'Expected response:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="MCP Server", resource="https://mcp.example.com"
- Test with valid token:
curl -X POST http://localhost:8080/mcp \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'MCP Framework supports two token validation strategies, each with different trade-offs:
How it works: The framework fetches public keys from your authorization server's JWKS endpoint and validates JWT signatures locally.
Pros:
- ⚡ Fast: No network call required for each request (after key caching)
- 🔒 Secure: Cryptographic signature validation
- 📉 Low latency: ~10ms validation time (cached keys)
- 💰 Cost-effective: Reduces load on authorization server
Cons:
- ⏱️ Revocation delay: Tokens remain valid until expiration (can't revoke immediately)
- 🔑 Key management: Requires JWKS endpoint with proper key rotation
- 💾 Stateless only: No way to check token status in real-time
Best for:
- High-performance APIs
- Microservices architectures
- Short-lived tokens (15-60 minutes)
- Systems without real-time revocation needs
Configuration:
validation: {
type: 'jwt',
jwksUri: "https://auth.example.com/.well-known/jwks.json",
audience: "https://mcp.example.com",
issuer: "https://auth.example.com",
algorithms: ['RS256', 'ES256'] // Optional, defaults to RS256 and ES256
}Performance characteristics:
- First request (cache miss): ~150-200ms
- Cached requests: ~5-10ms
- JWKS cache TTL: 15 minutes (configurable)
How it works: For each request, the framework calls your authorization server's introspection endpoint to check if the token is valid.
Pros:
- ⚡ Real-time revocation: Tokens can be revoked immediately
- 📊 Centralized control: Auth server has full control over token validity
- 🎯 Accurate: Always reflects current token status
- 🔍 Auditable: All validation requests logged at auth server
Cons:
- 🐌 Slower: Network call required for each validation (even with caching)
- 📈 Higher latency: ~50-100ms (cached) to ~200-300ms (uncached)
- 💰 Higher load: More requests to authorization server
- 🌐 Network dependent: Requires reliable connection to auth server
Best for:
- Systems requiring real-time token revocation
- Long-lived tokens (hours to days)
- Compliance requirements (audit trail)
- Scenarios with frequent permission changes
Configuration:
validation: {
type: 'introspection',
audience: "https://mcp.example.com",
issuer: "https://auth.example.com",
introspection: {
endpoint: "https://auth.example.com/oauth/introspect",
clientId: "mcp-server",
clientSecret: process.env.OAUTH_CLIENT_SECRET
}
}Performance characteristics:
- First request (cache miss): ~200-300ms
- Cached requests: ~20-50ms
- Cache TTL: 5 minutes (configurable)
| Factor | JWT Validation | Token Introspection |
|---|---|---|
| Performance | ⭐⭐⭐⭐⭐ Excellent | ⭐⭐⭐ Good |
| Revocation | ⭐⭐ Delayed | ⭐⭐⭐⭐⭐ Immediate |
| Complexity | ⭐⭐⭐ Moderate | ⭐⭐⭐⭐ Simple |
| Auth Server Load | ⭐⭐⭐⭐⭐ Very Low | ⭐⭐⭐ Moderate |
| Network Dependency | ⭐⭐⭐⭐ Low | ⭐⭐ High |
Recommendation:
- Use JWT validation for most use cases (better performance)
- Use token introspection when you need real-time revocation
Auth0 is a popular identity platform that provides OAuth 2.1 support out of the box.
-
Create an Auth0 Application:
- Log in to Auth0 Dashboard
- Go to Applications → Create Application
- Choose "Machine to Machine Application"
- Select your Auth0 API (or create one)
-
Get Configuration Values:
- Domain: Your Auth0 tenant domain (e.g.,
your-tenant.auth0.com) - Issuer:
https://your-tenant.auth0.com/ - JWKS URI:
https://your-tenant.auth0.com/.well-known/jwks.json - Audience: Your API identifier (e.g.,
https://mcp.example.com)
- Domain: Your Auth0 tenant domain (e.g.,
-
Configure Your MCP Server:
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [`https://${process.env.AUTH0_DOMAIN}`],
resource: process.env.AUTH0_AUDIENCE,
validation: {
type: 'jwt',
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
audience: process.env.AUTH0_AUDIENCE,
issuer: `https://${process.env.AUTH0_DOMAIN}/`
}
})
}
}
}
});
await server.start();- Environment Variables (.env):
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://mcp.example.comGet a test token using Auth0's test endpoint:
curl --request POST \
--url https://your-tenant.auth0.com/oauth/token \
--header 'content-type: application/json' \
--data '{
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET",
"audience": "https://mcp.example.com",
"grant_type": "client_credentials"
}'Use the returned token to test your MCP server:
curl -X POST http://localhost:8080/mcp \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'Okta is an enterprise identity platform with comprehensive OAuth 2.1 support.
-
Create an Okta Application:
- Log in to Okta Admin Console
- Go to Applications → Create App Integration
- Choose "API Services" (OAuth 2.0)
- Give it a name (e.g., "MCP Server")
-
Configure Authorization Server:
- Go to Security → API
- Use the "default" authorization server or create a custom one
- Note your authorization server's issuer URL
-
Get Configuration Values:
- Issuer:
https://your-domain.okta.com/oauth2/default(or your custom auth server) - JWKS URI:
https://your-domain.okta.com/oauth2/default/v1/keys - Audience: Your API identifier (configure in authorization server)
- Issuer:
-
Configure Your MCP Server:
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [process.env.OKTA_ISSUER],
resource: process.env.OKTA_AUDIENCE,
validation: {
type: 'jwt',
jwksUri: `${process.env.OKTA_ISSUER}/v1/keys`,
audience: process.env.OKTA_AUDIENCE,
issuer: process.env.OKTA_ISSUER
}
})
}
}
}
});
await server.start();- Environment Variables (.env):
OKTA_ISSUER=https://your-domain.okta.com/oauth2/default
OKTA_AUDIENCE=api://mcp-servercurl --request POST \
--url https://your-domain.okta.com/oauth2/default/v1/token \
--header 'accept: application/json' \
--header 'content-type: application/x-www-form-urlencoded' \
--data 'grant_type=client_credentials&scope=your_scope&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET'AWS Cognito provides user pools and identity pools with OAuth 2.1 support.
-
Create a User Pool:
- Go to AWS Cognito Console
- Create a new user pool
- Configure app client (enable client credentials flow)
-
Create Resource Server (Optional):
- In your user pool, go to "App integration" → "Resource servers"
- Create a resource server with identifier (e.g.,
https://mcp.example.com) - Define custom scopes if needed
-
Get Configuration Values:
- Issuer:
https://cognito-idp.{region}.amazonaws.com/{user-pool-id} - JWKS URI:
https://cognito-idp.{region}.amazonaws.com/{user-pool-id}/.well-known/jwks.json - Audience: Your app client ID
- Issuer:
-
Configure Your MCP Server:
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [process.env.COGNITO_ISSUER],
resource: process.env.COGNITO_AUDIENCE,
validation: {
type: 'jwt',
jwksUri: `${process.env.COGNITO_ISSUER}/.well-known/jwks.json`,
audience: process.env.COGNITO_AUDIENCE,
issuer: process.env.COGNITO_ISSUER
}
})
}
}
}
});
await server.start();- Environment Variables (.env):
COGNITO_ISSUER=https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX
COGNITO_AUDIENCE=1234567890abcdefghijklmnop
AWS_REGION=us-east-1curl -X POST https://your-domain.auth.us-east-1.amazoncognito.com/oauth2/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&scope=your_resource_server/scope'Microsoft Entra ID (formerly Azure AD) provides enterprise OAuth 2.1 support.
-
Register an Application:
- Go to Azure Portal
- Azure Active Directory → App registrations → New registration
- Name your application (e.g., "MCP Server")
-
Configure API Permissions:
- In your app registration, go to "Expose an API"
- Add an Application ID URI (e.g.,
api://mcp-server) - Add scopes if needed
-
Create Client Credentials:
- Go to "Certificates & secrets"
- Create a new client secret
- Save the secret value
-
Get Configuration Values:
- Issuer:
https://login.microsoftonline.com/{tenant-id}/v2.0 - JWKS URI:
https://login.microsoftonline.com/{tenant-id}/discovery/v2.0/keys - Audience: Your Application ID URI
- Issuer:
-
Configure Your MCP Server:
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [
`https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`
],
resource: process.env.AZURE_AUDIENCE,
validation: {
type: 'jwt',
jwksUri: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/discovery/v2.0/keys`,
audience: process.env.AZURE_AUDIENCE,
issuer: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`
}
})
}
}
}
});
await server.start();- Environment Variables (.env):
AZURE_TENANT_ID=your-tenant-id
AZURE_CLIENT_ID=your-client-id
AZURE_CLIENT_SECRET=your-client-secret
AZURE_AUDIENCE=api://mcp-servercurl -X POST https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&scope=api://mcp-server/.default'If you're running your own OAuth authorization server, ensure it's RFC-compliant:
Your authorization server must support:
- RFC 6749: OAuth 2.0 Authorization Framework
- RFC 8414: Authorization Server Metadata (recommended)
- RFC 7517: JSON Web Key (JWK) for JWT validation
- RFC 7662: Token Introspection (if using introspection)
- RFC 6750: Bearer Token Usage
For JWT validation:
/.well-known/jwks.json- JWKS endpoint with public keys
For Token introspection:
/oauth/introspect- Token introspection endpoint (RFC 7662)
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080,
auth: {
provider: new OAuthAuthProvider({
authorizationServers: ["https://your-auth-server.com"],
resource: "https://mcp.example.com",
validation: {
type: 'jwt',
jwksUri: "https://your-auth-server.com/.well-known/jwks.json",
audience: "https://mcp.example.com",
issuer: "https://your-auth-server.com"
}
})
}
}
}
});
await server.start();Verify your authorization server is properly configured:
# Test JWKS endpoint
curl https://your-auth-server.com/.well-known/jwks.json
# Test authorization server metadata (optional but recommended)
curl https://your-auth-server.com/.well-known/oauth-authorization-serverMCP Framework supports multiple authorization servers (useful for federation):
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [
"https://primary-auth.example.com",
"https://backup-auth.example.com",
"https://partner-auth.example.com"
],
resource: "https://mcp.example.com",
validation: {
type: 'jwt',
jwksUri: "https://primary-auth.example.com/.well-known/jwks.json",
audience: "https://mcp.example.com",
issuer: "https://primary-auth.example.com"
}
})
}
}
}
});Adjust cache TTLs for your use case:
import { JWTValidator, IntrospectionValidator } from "mcp-framework";
// Custom JWT validator with shorter cache
const jwtValidator = new JWTValidator({
jwksUri: "https://auth.example.com/.well-known/jwks.json",
audience: "https://mcp.example.com",
issuer: "https://auth.example.com",
cacheTTL: 600000 // 10 minutes (default: 15 minutes)
});
// Custom introspection validator with longer cache
const introspectionValidator = new IntrospectionValidator({
endpoint: "https://auth.example.com/oauth/introspect",
clientId: "mcp-server",
clientSecret: process.env.CLIENT_SECRET,
cacheTTL: 600000 // 10 minutes (default: 5 minutes)
});Control which endpoints require authentication:
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
auth: {
provider: new OAuthAuthProvider({
// ... OAuth config
}),
endpoints: {
initialize: true, // Require auth for session creation
messages: true // Require auth for MCP messages
}
}
}
}
});Always use HTTPS in production. OAuth tokens transmitted over HTTP can be intercepted.
// ❌ DO NOT use in production
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
port: 8080, // Unencrypted HTTP
auth: { /* OAuth config */ }
}
}
});
// ✅ Production setup (behind HTTPS proxy/load balancer)
// Use nginx, Caddy, or AWS ALB to terminate TLSClient-side recommendations:
- Store tokens in secure, httpOnly cookies or secure storage
- Never store tokens in localStorage (XSS vulnerability)
- Use short-lived access tokens (15-60 minutes)
- Implement token refresh flow
Audience validation prevents token reuse across different services:
// Each service should have a unique audience
const apiServer = new OAuthAuthProvider({
resource: "https://api.example.com", // ← Unique audience
validation: {
audience: "https://api.example.com" // ← Must match
}
});
const mcpServer = new OAuthAuthProvider({
resource: "https://mcp.example.com", // ← Different audience
validation: {
audience: "https://mcp.example.com" // ← Must match
}
});While MCP Framework validates tokens, you can implement scope-based authorization in your tools:
import { MCPTool, McpInput } from "mcp-framework";
import { z } from "zod";
class AdminTool extends MCPTool {
name = "admin_action";
description = "Admin-only action";
schema = z.object({
action: z.string().describe("Action to perform")
});
async execute(input: McpInput<this>, context?: any) {
// Access token claims from auth context
const claims = context?.auth?.data;
if (!claims?.scope?.includes('admin')) {
throw new Error('Insufficient permissions');
}
// Perform admin action
return "Admin action completed";
}
}Cause: JWKS endpoint returning wrong keys or keys don't match token
Solution:
# Verify JWKS endpoint is accessible
curl https://your-auth-server.com/.well-known/jwks.json
# Check token header for 'kid' (Key ID)
echo "YOUR_TOKEN" | cut -d'.' -f1 | base64 -d | jq
# Ensure kid matches a key in JWKSCause: Token's aud claim doesn't match configured audience
Solution:
// Ensure audience matches in both OAuth config and token
validation: {
audience: "https://mcp.example.com" // Must match token's aud claim
}Debug the token:
# Decode token to check audience
echo "YOUR_TOKEN" | cut -d'.' -f2 | base64 -d | jq .audCause: Token's exp claim is in the past
Solution:
- Request a new token from your authorization server
- Check system clock synchronization (tokens use Unix timestamps)
- Reduce token lifetime if tokens expire too quickly
Cause: Network issues or wrong JWKS URI
Solution:
# Test JWKS endpoint
curl -v https://your-auth-server.com/.well-known/jwks.json
# Check DNS resolution
nslookup your-auth-server.com
# Check firewall rulesCause: Introspection endpoint credentials incorrect or endpoint unavailable
Solution:
// Verify introspection config
introspection: {
endpoint: "https://auth.example.com/oauth/introspect", // Check URL
clientId: "mcp-server", // Verify client ID
clientSecret: process.env.OAUTH_CLIENT_SECRET // Check secret
}Test introspection manually:
curl -X POST https://auth.example.com/oauth/introspect \
-u "client-id:client-secret" \
-d "token=YOUR_TOKEN"Enable debug logging to troubleshoot OAuth issues:
# Enable debug logging
MCP_DEBUG_CONSOLE=true node dist/index.js
# Enable file logging
MCP_ENABLE_FILE_LOGGING=true MCP_LOG_DIRECTORY=logs node dist/index.jsLook for OAuth-related log messages:
[INFO] OAuthAuthProvider initialized with JWT validation
[DEBUG] Token claims - sub: user-123, scope: read write
[ERROR] OAuth authentication failed: Token has expired
Test your OAuth setup with curl:
# 1. Get metadata endpoint
curl http://localhost:8080/.well-known/oauth-protected-resource
# 2. Try without token (should fail with 401)
curl -v -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
# 3. Try with invalid token (should fail with 401)
curl -v -X POST http://localhost:8080/mcp \
-H "Authorization: Bearer invalid-token" \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
# 4. Try with valid token (should succeed)
curl -v -X POST http://localhost:8080/mcp \
-H "Authorization: Bearer YOUR_VALID_TOKEN" \
-H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'If you're currently using the simple JWT provider:
Before (JWT Provider):
import { MCPServer, JWTAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "sse",
options: {
auth: {
provider: new JWTAuthProvider({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"]
})
}
}
}
});After (OAuth Provider):
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "sse",
options: {
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [process.env.OAUTH_ISSUER],
resource: process.env.OAUTH_RESOURCE,
validation: {
type: 'jwt',
jwksUri: process.env.OAUTH_JWKS_URI,
audience: process.env.OAUTH_AUDIENCE,
issuer: process.env.OAUTH_ISSUER
}
})
}
}
}
});Key differences:
- OAuth uses asymmetric keys (RS256/ES256) instead of symmetric (HS256)
- Tokens must come from a proper authorization server
- Automatic metadata endpoint at
/.well-known/oauth-protected-resource - Better security with audience validation
Before (API Key):
import { MCPServer, APIKeyAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
auth: {
provider: new APIKeyAuthProvider({
keys: [process.env.API_KEY]
})
}
}
}
});After (OAuth):
import { MCPServer, OAuthAuthProvider } from "mcp-framework";
const server = new MCPServer({
transport: {
type: "http-stream",
options: {
auth: {
provider: new OAuthAuthProvider({
authorizationServers: [process.env.OAUTH_ISSUER],
resource: process.env.OAUTH_RESOURCE,
validation: {
type: 'jwt',
jwksUri: process.env.OAUTH_JWKS_URI,
audience: process.env.OAUTH_AUDIENCE,
issuer: process.env.OAUTH_ISSUER
}
})
}
}
}
});Migration steps:
- Set up an OAuth authorization server (Auth0, Okta, etc.)
- Update environment variables
- Update client applications to obtain OAuth tokens
- Test with both old and new auth (if gradual migration)
- Switch over and retire API keys
- MCP Specification - OAuth 2.1
- RFC 9728 - OAuth 2.0 Protected Resource Metadata
- RFC 8414 - OAuth 2.0 Authorization Server Metadata
- RFC 6750 - Bearer Token Usage
- RFC 7662 - Token Introspection
- OAuth 2.1 Draft Specification
Need help? Open an issue on GitHub or check the documentation.