| title | OAuth2 Server Implementation |
|---|---|
| description | Developer guide for the OAuth2 authorization server that enables programmatic API access via Bearer tokens |
| sidebarTitle | OAuth2 Server |
- User → DeployStack OAuth (Social Login) - See OAuth Providers
- MCP Client → DeployStack OAuth (API Access) - This document - How VS Code, Cursor, Claude.ai authenticate to satellite APIs
- User → MCP Server OAuth (External Service Access) - See MCP Server OAuth - How users authorize Notion, Box, Linear
This document covers system #2 - the OAuth2 authorization server for MCP client authentication.
This document describes the OAuth2 authorization server implementation in the DeployStack backend, which enables CLI tools and applications to access APIs using Bearer tokens. For general authentication, see Backend Authentication System.
The OAuth2 server provides RFC 6749 compliant authorization for programmatic API access with RFC 7591 Dynamic Client Registration support. This enables the DeployStack Satellite, MCP clients (VS Code, Cursor, Claude.ai), and other tools to authenticate users and access APIs on their behalf using Bearer tokens instead of cookies.
The OAuth2 server implementation includes:
- Authorization Server - Handles OAuth2 authorization flow with PKCE
- Dynamic Client Registration - RFC 7591 compliant client registration for MCP clients
- Token Management - Issues and validates access/refresh tokens
- Consent System - User authorization interface
- Dual Authentication - Supports both cookies and Bearer tokens
- Scope-based Access - Fine-grained permission control
- Database Storage - Persistent client and token storage
The implementation follows the OAuth2 Authorization Code flow enhanced with PKCE (Proof Key for Code Exchange) for additional security:
- Client generates PKCE challenge - Creates code verifier and SHA256 challenge
- Authorization request - Client redirects to
/api/oauth2/auth - User consent - User approves requested scopes
- Authorization code - Server returns code to callback
- Token exchange - Client exchanges code for tokens
- API access - Client uses Bearer token for requests
MCP clients can automatically register themselves:
- Client registration - POST to
/api/oauth2/registerwith metadata - Client validation - Server validates redirect URIs and grants
- Client ID generation - Server generates unique client_id (format:
dyn_<timestamp>_<random>) - Database storage - Client metadata stored in
dynamic_oauth_clientstable - OAuth flow - Client proceeds with standard authorization flow
PKCE provides security for public clients (like CLI tools and MCP clients):
- 128 random bytes encoded as base64url
- Generated by client, kept secret
- Used during token exchange
- SHA256 hash of verifier
- Sent with authorization request
- Stored with authorization code
- Server verifies challenge matches verifier
- Prevents code interception attacks
- Required for all authorization requests
Manages the authorization flow:
- Validates dynamic clients against database (
dynamic_oauth_clientstable) - Supports both pre-registered and dynamically registered clients
- Extensible for additional client types
- Checks URI against allowed patterns for MCP clients
- Supports localhost callbacks for CLI tools
- Supports VS Code specific patterns (
http://127.0.0.1:<port>/,vscode://) - Supports Cursor patterns (
cursor://) - Supports Claude.ai patterns (
https://claude.ai/mcp/auth/callback) - Prevents redirect attacks
- Validates requested scopes against MCP scope patterns
- Supports
mcp:read,mcp:tools:execute,offline_access - Ensures scopes are recognized
- Limits access appropriately
- Stores authorization requests in database
- Links PKCE challenges
- Manages request lifecycle with expiration
- Supports team-scoped authorization
- Creates authorization codes
- Associates with user session and team
- Implements 10-minute expiration
- Prevents replay attacks
- Validates authorization codes against database
- Verifies PKCE challenge
- Ensures single use
- Validates client and redirect URI match
Implements RFC 7591 Dynamic Client Registration:
- File:
services/backend/src/routes/oauth2/register.ts - Endpoint:
POST /api/oauth2/register - Purpose: Allows MCP clients to self-register
- Validates
redirect_urisagainst MCP client patterns - Supports VS Code:
http://127.0.0.1:<port>/,https://vscode.dev/redirect - Supports Cursor:
cursor://schemes - Supports Claude.ai:
https://claude.ai/mcp/auth/callback - Validates
grant_types(authorization_code, refresh_token) - Validates
response_types(code)
- Format:
dyn_<timestamp>_<random> - Timestamp: Unix timestamp for uniqueness
- Random suffix: 9-character base36 string
- Example:
dyn_1757880447836_uvze3d0yc
- Table:
dynamic_oauth_clients - Schema: See
services/backend/src/db/schema.ts - Fields: client_id, client_name, redirect_uris, grant_types, response_types, scope, token_endpoint_auth_method, client_id_issued_at, expires_at
- Persistence: Survives server restarts and supports multiple instances
Handles token lifecycle:
- Creates cryptographically secure tokens
- Generates appropriate expiration
- Stores hashed versions in database
- Issues 1-week access tokens for MCP clients
- Issues 1-hour access tokens for CLI tools
- Includes user, team, and scope data
- Enables API authentication
- Issues 30-day refresh tokens
- Allows token renewal
- Maintains session continuity
- Supports offline access
- Validates token format
- Checks expiration
- Verifies against database
- Supports introspection endpoint
- Exchanges refresh for access token
- Validates client identity
- Maintains scope consistency
- Supports both static and dynamic clients
- Invalidates tokens on demand
- Cleans up related tokens
- Ensures immediate effect
- File:
services/backend/src/db/schema.ts - Table:
dynamic_oauth_clients - Migration:
0006_keen_firestar.sql - Purpose: Persistent storage for dynamically registered MCP clients
- Table:
oauth_authorization_codes - Purpose: Stores authorization requests and codes
- Features: PKCE challenge storage, team context, expiration
- Table:
oauth_access_tokens - Purpose: Stores issued access tokens
- Features: Hashed storage, scope tracking, team context
- Table:
oauth_refresh_tokens - Purpose: Stores refresh tokens for token renewal
- Features: Long-term storage, client association
Automatic maintenance system needs implementation:
- Should run hourly via cron
- Remove expired authorization codes (>10 minutes)
- Remove expired access tokens
- Remove expired refresh tokens
- Clean up unused dynamic client registrations
- Authorization codes > 10 minutes old
- Expired access tokens
- Expired refresh tokens
- Dynamic clients unused for >90 days (configurable)
The OAuth2 server implements standard OAuth2 endpoints following RFC 6749 and RFC 7591:
- Authorization Endpoint (
/api/oauth2/auth) - Initiates the OAuth2 flow with PKCE parameters - Consent Endpoints (
/api/oauth2/consent) - Displays and processes user authorization consent - Token Endpoint (
/api/oauth2/token) - Exchanges authorization codes for access tokens and handles token refresh - User Info Endpoint (
/api/oauth2/userinfo) - Returns authenticated user information - Introspection Endpoint (
/api/oauth2/introspect) - Token validation for resource servers
- Registration Endpoint (
/api/oauth2/register) - RFC 7591 compliant client registration
For complete API specifications including request parameters, response schemas, and examples, see the Backend API Documentation. The API documentation provides OpenAPI specifications for all OAuth2 endpoints.
MCP Client Scopes:
mcp:read- Tool discovery and MCP server accessmcp:tools:execute- Tool execution permissionsoffline_access- Refresh token issuance
CLI Tool Scopes:
For the current list of CLI-supported scopes, see the source code at services/backend/src/services/oauth/authorizationService.ts in the validateScope() method.
Scopes are enforced at the endpoint level:
requireOAuthScope()- Single scope requirementrequireAnyOAuthScope()- Multiple scope options- Skip enforcement for cookie auth
- Validates token contains required scope
- Returns 403 for insufficient scope
- Provides clear error messages
VS Code MCP Extension:
- Client ID: Auto-generated (e.g.,
dyn_1757880447836_uvze3d0yc) - Registration: Automatic via RFC 7591
- Redirect URIs:
http://127.0.0.1:<port>/,https://vscode.dev/redirect - Scopes:
mcp:read mcp:tools:execute offline_access - Token Lifetime: 1-week access, 30-day refresh
Cursor MCP Client:
- Client ID: Auto-generated
- Registration: Automatic via RFC 7591
- Redirect URIs:
cursor://schemes - Scopes:
mcp:read mcp:tools:execute offline_access
Claude.ai MCP Client:
- Client ID: Auto-generated
- Registration: Automatic via RFC 7591
- Redirect URIs:
https://claude.ai/mcp/auth/callback - Scopes:
mcp:read mcp:tools:execute offline_access
To support additional pre-registered OAuth2 clients:
- Add client_id to validation whitelist in
AuthorizationService.validateClient() - Configure allowed redirect URIs in
AuthorizationService.validateRedirectUri() - Define client-specific settings
- Update documentation
Endpoints can accept cookies or Bearer tokens:
- First checks cookie session (from authHook)
- Falls back to Bearer token validation
- Populates unified
request.user - Maintains authentication type context
Routes support both authentication methods:
- Define both security schemes in OpenAPI
- Use dual authentication middleware
- Apply scope requirements conditionally
- Handle both response formats
The system maintains context about authentication:
- Cookie Auth:
request.userandrequest.session - OAuth2 Auth:
request.userandrequest.tokenPayload - Type Detection: Check for
tokenPayloadpresence - Unified Interface: Same user object structure
Protection against authorization code interception:
- Required for all authorization requests
- SHA256 challenge method only
- Cryptographically secure verifier generation
- Single-use authorization codes
Multiple layers of token protection:
- Argon2 hashing for stored tokens
- Constant-time comparison
- Secure random generation
- Automatic expiration
- Regular cleanup (TODO: implement)
Secure authorization flow:
- CSRF protection via state parameter
- Proper URL encoding of state parameter
- Session requirement for authorization
- Validated redirect URIs
- Clear consent interface
API access security:
- Standard Authorization header
- Token validation on each request
- Scope-based access control
- Automatic token refresh
RFC 7591 security measures:
- Redirect URI validation against MCP patterns
- Client metadata validation
- Automatic client ID generation
- Database persistence with proper indexing
- No client secrets for public clients
Example dynamic client registration for MCP clients:
- Client registration request
- Server validates metadata
- Client ID generated and stored
- Client proceeds with OAuth flow
- User authorizes in browser
- Tokens issued for MCP access
Example OAuth2 flow for CLI tools:
- Generate PKCE challenge
- Open browser for authorization
- Start callback server
- User approves in browser
- Receive authorization code
- Exchange for tokens
- Store tokens securely
- Use Bearer token for API
Using Bearer token for API access:
GET /api/teams/me/default
Authorization: Bearer <access_token>
Refreshing expired access token:
POST /api/oauth2/token
Content-Type: application/json
{
"grant_type": "refresh_token",
"refresh_token": "<refresh_token>",
"client_id": "dyn_1757880447836_uvze3d0yc"
}
- Authorization requests
- Dynamic client registrations
- Token issuance rate
- Refresh token usage
- Failed authentication attempts
- Cleanup effectiveness
Comprehensive logging for debugging:
- Authorization flow steps
- Dynamic client registration events
- Token operations
- Scope validations
- Error conditions
- Security events
The backend validates OAuth scopes to control API access. Scope configuration must stay synchronized between the backend and clients.
For the current list of supported scopes, check the source code at:
- Backend validation:
services/backend/src/services/oauth/authorizationService.tsin thevalidateScope()method
When adding support for a new OAuth scope in the backend:
- Add the scope to the
allowedScopesarray inservices/backend/src/services/oauth/authorizationService.ts - Update clients to request the new scope (Satellite, MCP clients)
- Apply scope enforcement to relevant API endpoints using middleware
- Test the complete flow to ensure proper scope validation
Example:
// In services/backend/src/services/oauth/authorizationService.ts
static validateScope(scope: string): boolean {
const requestedScopes = scope.split(' ');
const allowedScopes = [
'mcp:read',
'mcp:tools:execute',
'offline_access',
'your-new-scope', // Add new scope here
// ... other scopes
];
return requestedScopes.every(s => allowedScopes.includes(s));
}Apply scope requirements to API endpoints:
// Single scope requirement
server.get('/api/your-endpoint', {
preValidation: [
requireValidAccessToken(),
requireOAuthScope('your-new-scope')
]
}, async (request, reply) => {
// Your endpoint logic
});
// Multiple scope options
server.get('/api/another-endpoint', {
preValidation: [
requireValidAccessToken(),
requireAnyOAuthScope(['scope1', 'scope2'])
]
}, async (request, reply) => {
// Your endpoint logic
});Critical: The backend and clients must have matching scope configurations:
- If backend supports a scope but client doesn't request it, users won't get that permission
- If client requests a scope but backend doesn't support it, authentication will fail
Always coordinate scope changes between backend and client implementations.
The OAuth2 server supports MCP clients through dynamic registration:
- VS Code MCP Extension - Automatic registration and authentication
- Cursor MCP Client - Dynamic client registration support
- Claude.ai Custom Connector - OAuth2 integration
- Cline MCP Client - VS Code extension support
- Dynamic Registration - Client registers via RFC 7591
- OAuth Authorization - User authorizes in browser
- Token Issuance - Long-lived tokens for MCP access
- MCP Communication - Bearer tokens for satellite access
- RFC 6749 OAuth2 Authorization Server
- RFC 7591 Dynamic Client Registration
- PKCE support for public clients
- Database-backed client and token storage
- Team-scoped authorization
- MCP client support (VS Code, Cursor, Claude.ai)
- Dual authentication (cookies + Bearer tokens)
- Scope-based access control
- Token introspection endpoint
- State parameter URL encoding fix
- OAuthCleanupService Implementation - Automated cleanup of expired tokens and clients
- Comprehensive Logging - Enhanced logging for monitoring and debugging
- Metrics Collection - Performance and usage metrics
- Rate Limiting - Protection against abuse
- Client Management UI - Admin interface for client management
- Backend Authentication System - Core authentication
- Satellite OAuth Authentication - MCP client authentication
- Security Policy - Security details
- API Documentation - API reference
- OAuth Provider Implementation - Third-party OAuth login setup