Phase 4: Create standalone authorization server
- Created auth-server/index.ts with full OAuth endpoint support - Reuses EverythingAuthProvider from main server - Added custom /oauth/introspect endpoint for token validation - Includes fake upstream auth routes for user authentication - Added TypeScript configuration for auth server - Added comprehensive npm scripts for all modes: - dev:integrated, dev:separate, dev:auth-server - dev:with-separate-auth (runs both servers) - build:auth-server, build:all - Added concurrently dependency for running multiple servers - Added detailed README for auth server - Successfully serves OAuth metadata and health endpoints
This commit is contained in:
parent
4771c6eb34
commit
5c408eb43d
3 changed files with 381 additions and 2 deletions
89
auth-server/README.md
Normal file
89
auth-server/README.md
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
# MCP Standalone Authorization Server
|
||||
|
||||
This is a demonstration OAuth 2.0 authorization server for MCP.
|
||||
|
||||
## Purpose
|
||||
|
||||
This server demonstrates how MCP servers can delegate authentication to a separate
|
||||
authorization server (Mode 2 in our implementation). In production environments,
|
||||
you would typically use established OAuth providers like:
|
||||
|
||||
- Auth0
|
||||
- Okta
|
||||
- Google OAuth
|
||||
- GitHub OAuth
|
||||
- Microsoft Azure AD
|
||||
|
||||
## Architecture
|
||||
|
||||
When running in separate mode, the architecture looks like:
|
||||
|
||||
1. MCP Client (e.g., Inspector) discovers auth server URL from MCP server metadata
|
||||
2. Client registers and authenticates directly with this auth server
|
||||
3. Auth server issues tokens
|
||||
4. MCP server validates tokens by calling this auth server's introspection endpoint
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `/.well-known/oauth-authorization-server` - OAuth 2.0 server metadata
|
||||
- `/oauth/authorize` - Authorization endpoint
|
||||
- `/oauth/token` - Token endpoint
|
||||
- `/oauth/register` - Dynamic client registration
|
||||
- `/oauth/introspect` - Token introspection (for MCP server validation)
|
||||
- `/fakeupstreamauth/authorize` - Fake upstream auth page (demo only)
|
||||
- `/fakeupstreamauth/callback` - Fake upstream callback (demo only)
|
||||
- `/health` - Health check endpoint
|
||||
|
||||
## Development
|
||||
|
||||
This server shares Redis with the MCP server for development convenience.
|
||||
In production, these would typically be separate.
|
||||
|
||||
## Running the Auth Server
|
||||
|
||||
### Standalone
|
||||
```bash
|
||||
# From the repository root
|
||||
npm run dev:auth-server
|
||||
```
|
||||
|
||||
### With MCP Server (Separate Mode)
|
||||
```bash
|
||||
# Start both servers together
|
||||
npm run dev:with-separate-auth
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Health Check
|
||||
```bash
|
||||
curl http://localhost:3001/health
|
||||
```
|
||||
|
||||
### OAuth Metadata
|
||||
```bash
|
||||
curl http://localhost:3001/.well-known/oauth-authorization-server
|
||||
```
|
||||
|
||||
### With MCP Inspector
|
||||
1. Start this auth server: `npm run dev:auth-server`
|
||||
2. Start MCP server in separate mode: `AUTH_MODE=separate npm run dev`
|
||||
3. Open Inspector: `npx -y @modelcontextprotocol/inspector`
|
||||
4. Connect to `http://localhost:3232`
|
||||
5. Auth flow will redirect to this server (port 3001)
|
||||
|
||||
## Configuration
|
||||
|
||||
The auth server uses the same environment variables as the main server:
|
||||
- `AUTH_SERVER_PORT` - Port to run on (default: 3001)
|
||||
- `AUTH_SERVER_URL` - Base URL (default: http://localhost:3001)
|
||||
- `REDIS_URL` - Redis connection (shared with MCP server)
|
||||
|
||||
## Production Considerations
|
||||
|
||||
In production:
|
||||
- Use real OAuth providers instead of this demonstration server
|
||||
- Separate Redis instances for auth and resource servers
|
||||
- Enable HTTPS with proper certificates
|
||||
- Implement proper rate limiting and monitoring
|
||||
- Use secure client secrets and token rotation
|
||||
146
auth-server/index.ts
Normal file
146
auth-server/index.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';
|
||||
import { EverythingAuthProvider } from '../src/auth/provider.js';
|
||||
import { handleFakeAuthorize, handleFakeAuthorizeRedirect } from '../src/handlers/fakeauth.js';
|
||||
import { redisClient } from '../src/redis.js';
|
||||
import { logger } from '../src/utils/logger.js';
|
||||
import { AUTH_SERVER_PORT, AUTH_SERVER_URL } from '../src/config.js';
|
||||
|
||||
const app = express();
|
||||
|
||||
console.log('=====================================');
|
||||
console.log('MCP Demonstration Authorization Server');
|
||||
console.log('=====================================');
|
||||
console.log('This standalone server demonstrates OAuth 2.0');
|
||||
console.log('authorization separate from the MCP resource server');
|
||||
console.log('');
|
||||
console.log('This is for demonstration purposes only.');
|
||||
console.log('In production, you would use a real OAuth provider');
|
||||
console.log('like Auth0, Okta, Google, GitHub, etc.');
|
||||
console.log('=====================================');
|
||||
|
||||
// CORS for Inspector and MCP server
|
||||
app.use(cors({
|
||||
origin: true,
|
||||
credentials: true
|
||||
}));
|
||||
|
||||
app.use(express.json());
|
||||
app.use(logger.middleware());
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({
|
||||
status: 'healthy',
|
||||
mode: 'authorization-server',
|
||||
endpoints: {
|
||||
metadata: `${AUTH_SERVER_URL}/.well-known/oauth-authorization-server`,
|
||||
authorize: `${AUTH_SERVER_URL}/oauth/authorize`,
|
||||
token: `${AUTH_SERVER_URL}/oauth/token`,
|
||||
register: `${AUTH_SERVER_URL}/oauth/register`,
|
||||
introspect: `${AUTH_SERVER_URL}/oauth/introspect`
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Create auth provider instance for reuse
|
||||
const authProvider = new EverythingAuthProvider();
|
||||
|
||||
// OAuth endpoints via SDK's mcpAuthRouter
|
||||
app.use(mcpAuthRouter({
|
||||
provider: authProvider,
|
||||
issuerUrl: new URL(AUTH_SERVER_URL),
|
||||
tokenOptions: {
|
||||
rateLimit: { windowMs: 5000, limit: 100 }
|
||||
},
|
||||
clientRegistrationOptions: {
|
||||
rateLimit: { windowMs: 60000, limit: 10 }
|
||||
}
|
||||
}));
|
||||
|
||||
// Token introspection endpoint (RFC 7662)
|
||||
app.post('/oauth/introspect', express.urlencoded({ extended: false }), async (req, res) => {
|
||||
try {
|
||||
const { token } = req.body;
|
||||
|
||||
if (!token) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: 'Missing token parameter' });
|
||||
}
|
||||
|
||||
// Verify the token using the auth provider
|
||||
const authInfo = await authProvider.verifyAccessToken(token);
|
||||
|
||||
// Return RFC 7662 compliant response
|
||||
res.json({
|
||||
active: true,
|
||||
client_id: authInfo.clientId,
|
||||
scope: authInfo.scopes.join(' '),
|
||||
exp: authInfo.expiresAt,
|
||||
sub: authInfo.extra?.userId || 'unknown',
|
||||
userId: authInfo.extra?.userId, // Custom field for our implementation
|
||||
username: authInfo.extra?.username,
|
||||
iss: AUTH_SERVER_URL,
|
||||
aud: authInfo.clientId,
|
||||
token_type: 'Bearer'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.debug('Token introspection failed', { error: (error as Error).message });
|
||||
|
||||
// Return inactive token response (don't leak error details)
|
||||
res.json({
|
||||
active: false
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Fake upstream auth endpoints (for user authentication simulation)
|
||||
app.get('/fakeupstreamauth/authorize', cors(), handleFakeAuthorize);
|
||||
app.get('/fakeupstreamauth/callback', cors(), handleFakeAuthorizeRedirect);
|
||||
|
||||
// Static assets (for auth page styling)
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
app.get('/mcp-logo.png', (req, res) => {
|
||||
// Serve from the main server's static directory
|
||||
const logoPath = path.join(__dirname, '../src/static/mcp.png');
|
||||
res.sendFile(logoPath);
|
||||
});
|
||||
|
||||
// Connect to Redis (shared with MCP server in dev)
|
||||
try {
|
||||
await redisClient.connect();
|
||||
logger.info('Connected to Redis', { url: redisClient.options?.url });
|
||||
} catch (error) {
|
||||
logger.error('Could not connect to Redis', error as Error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
app.listen(AUTH_SERVER_PORT, () => {
|
||||
logger.info('Authorization server started', {
|
||||
port: AUTH_SERVER_PORT,
|
||||
url: AUTH_SERVER_URL,
|
||||
endpoints: {
|
||||
metadata: `${AUTH_SERVER_URL}/.well-known/oauth-authorization-server`,
|
||||
authorize: `${AUTH_SERVER_URL}/oauth/authorize`,
|
||||
token: `${AUTH_SERVER_URL}/oauth/token`,
|
||||
register: `${AUTH_SERVER_URL}/oauth/register`,
|
||||
introspect: `${AUTH_SERVER_URL}/oauth/introspect`
|
||||
}
|
||||
});
|
||||
|
||||
console.log('');
|
||||
console.log('🚀 Auth server ready! Test with:');
|
||||
console.log(` curl ${AUTH_SERVER_URL}/health`);
|
||||
console.log(` curl ${AUTH_SERVER_URL}/.well-known/oauth-authorization-server`);
|
||||
console.log('');
|
||||
console.log('💡 To test separate mode:');
|
||||
console.log(' 1. Keep this server running');
|
||||
console.log(' 2. In another terminal: AUTH_MODE=separate npm run dev');
|
||||
console.log(' 3. Connect Inspector to http://localhost:3232');
|
||||
});
|
||||
9
auth-server/tsconfig.json
Normal file
9
auth-server/tsconfig.json
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../dist/auth-server",
|
||||
"rootDir": "../"
|
||||
},
|
||||
"include": ["index.ts", "../src/**/*.ts", "../shared/**/*.ts"],
|
||||
"exclude": ["../dist", "../node_modules", "../**/*.test.ts"]
|
||||
}
|
||||
Loading…
Reference in a new issue