Skip to content

Add Proxy OAuth Server Provider #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@
- [Low-Level Server](#low-level-server)
- [Writing MCP Clients](#writing-mcp-clients)
- [Server Capabilities](#server-capabilities)
- [Proxy OAuth Server](#proxy-authorization-requests-upstream)

## Overview

@@ -489,6 +490,52 @@ const result = await client.callTool({
});
```

### Proxy Authorization Requests Upstream

You can proxy OAuth requests to an external authorization provider:

```typescript
import express from 'express';
import { ProxyOAuthServerProvider, mcpAuthRouter } from '@modelcontextprotocol/sdk';

const app = express();

const proxyProvider = new ProxyOAuthServerProvider({
endpoints: {
authorizationUrl: "https://auth.external.com/oauth2/v1/authorize",
tokenUrl: "https://auth.external.com/oauth2/v1/token",
revocationUrl: "https://auth.external.com/oauth2/v1/revoke",
},
verifyAccessToken: async (token) => {
return {
token,
clientId: "123",
scopes: ["openid", "email", "profile"],
}
},
getClient: async (client_id) => {
return {
client_id,
redirect_uris: ["http://localhost:3000/callback"],
}
}
})

app.use(mcpAuthRouter({
provider: proxyProvider,
issuerUrl: new URL("http://auth.external.com"),
baseUrl: new URL("http://mcp.example.com"),
serviceDocumentationUrl: new URL("https://docs.example.com/"),
}))
```

This setup allows you to:
- Forward OAuth requests to an external provider
- Add custom token validation logic
- Manage client registrations
- Provide custom documentation URLs
- Maintain control over the OAuth flow while delegating to an external provider

## Documentation

- [Model Context Protocol documentation](https://modelcontextprotocol.io)
62 changes: 62 additions & 0 deletions src/server/auth/handlers/token.test.ts
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ import supertest from 'supertest';
import * as pkceChallenge from 'pkce-challenge';
import { InvalidGrantError, InvalidTokenError } from '../errors.js';
import { AuthInfo } from '../types.js';
import { ProxyOAuthServerProvider } from '../providers/proxyProvider.js';

// Mock pkce-challenge
jest.mock('pkce-challenge', () => ({
@@ -280,6 +281,67 @@ describe('Token Handler', () => {
expect(response.body.expires_in).toBe(3600);
expect(response.body.refresh_token).toBe('mock_refresh_token');
});

it('passes through code verifier when using proxy provider', async () => {
const originalFetch = global.fetch;

try {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({
access_token: 'mock_access_token',
token_type: 'bearer',
expires_in: 3600,
refresh_token: 'mock_refresh_token'
})
});

const proxyProvider = new ProxyOAuthServerProvider({
endpoints: {
authorizationUrl: 'https://example.com/authorize',
tokenUrl: 'https://example.com/token'
},
verifyAccessToken: async (token) => ({
token,
clientId: 'valid-client',
scopes: ['read', 'write'],
expiresAt: Date.now() / 1000 + 3600
}),
getClient: async (clientId) => clientId === 'valid-client' ? validClient : undefined
});

const proxyApp = express();
const options: TokenHandlerOptions = { provider: proxyProvider };
proxyApp.use('/token', tokenHandler(options));

const response = await supertest(proxyApp)
.post('/token')
.type('form')
.send({
client_id: 'valid-client',
client_secret: 'valid-secret',
grant_type: 'authorization_code',
code: 'valid_code',
code_verifier: 'any_verifier'
});

expect(response.status).toBe(200);
expect(response.body.access_token).toBe('mock_access_token');

expect(global.fetch).toHaveBeenCalledWith(
'https://example.com/token',
expect.objectContaining({
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: expect.stringContaining('code_verifier=any_verifier')
})
);
} finally {
global.fetch = originalFetch;
}
});
});

describe('Refresh token grant', () => {
16 changes: 11 additions & 5 deletions src/server/auth/handlers/token.ts
Original file line number Diff line number Diff line change
@@ -90,13 +90,19 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand

const { code, code_verifier } = parseResult.data;

// Verify PKCE challenge
const codeChallenge = await provider.challengeForAuthorizationCode(client, code);
if (!(await verifyChallenge(code_verifier, codeChallenge))) {
throw new InvalidGrantError("code_verifier does not match the challenge");
const skipLocalPkceValidation = provider.skipLocalPkceValidation;

// Perform local PKCE validation unless explicitly skipped
// (e.g. to validate code_verifier in upstream server)
if (!skipLocalPkceValidation) {
const codeChallenge = await provider.challengeForAuthorizationCode(client, code);
if (!(await verifyChallenge(code_verifier, codeChallenge))) {
throw new InvalidGrantError("code_verifier does not match the challenge");
}
}

const tokens = await provider.exchangeAuthorizationCode(client, code);
// Passes the code_verifier to the provider if PKCE validation didn't occur locally
const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined);
res.status(200).json(tokens);
break;
}
11 changes: 10 additions & 1 deletion src/server/auth/provider.ts
Original file line number Diff line number Diff line change
@@ -36,7 +36,7 @@ export interface OAuthServerProvider {
/**
* Exchanges an authorization code for an access token.
*/
exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise<OAuthTokens>;
exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string): Promise<OAuthTokens>;

/**
* Exchanges a refresh token for an access token.
@@ -54,4 +54,13 @@ export interface OAuthServerProvider {
* If the given token is invalid or already revoked, this method should do nothing.
*/
revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise<void>;

/**
* Whether to skip local PKCE validation.
*
* If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server.
*
* NOTE: This should only be true if the upstream server is performing the actual PKCE validation.
*/
skipLocalPkceValidation?: boolean;
}
Loading