该介绍目前仅提供英文版本。
A robust OAuth 2.1 provider framework specifically designed for Cloudflare Workers, featuring PKCE support, automatic token management, and enterprise-grade security with end-to-end encryption.
Project Overview
This TypeScript library implements the provider side of the OAuth 2.1 protocol, enabling developers to build secure authorization servers directly on Cloudflare’s edge infrastructure. The library acts as a wrapper around your Worker code, seamlessly adding OAuth authorization to your API endpoints.
Key Features
🛡️ Security First
- OAuth 2.1 Compliance: Full implementation of the latest OAuth 2.1 specification
- PKCE Support: Built-in Proof Key for Code Exchange for enhanced security
- End-to-End Encryption: All sensitive data encrypted using token-derived keys
- Single-Use Refresh Tokens: Advanced token rotation with fault tolerance
⚡ Edge-Optimized Performance
- Global Distribution: Runs on Cloudflare’s worldwide edge network
- Automatic Token Management: No manual token lifecycle management required
- KV Storage Integration: Leverages Workers KV for scalable token storage
- Low Latency: Sub-100ms response times globally
🔧 Developer Experience
- TypeScript Native: Full type safety and IntelliSense support
- Simple Integration: Minimal setup with wrapper-based architecture
- Flexible API: Comprehensive client and grant management tools
- Custom Error Handling: Configurable error responses and notifications
Quick Start
Installation
npm install @cloudflare/workers-oauth-provider
Basic Implementation
import { OAuthProvider } from '@cloudflare/workers-oauth-provider';
const oauthProvider = new OAuthProvider({
// Required: KV namespace for token storage
kv: env.OAUTH_KV,
// Client lookup function
lookupClient: async (clientId: string) => {
// Return client configuration or null if not found
return {
redirectUris: ['https://example.com/callback'],
scopes: ['read', 'write']
};
},
// Authorization handler
onAuthorize: async (request, { clientId, userId, scope }) => {
// Your authorization logic here
return {
allow: true,
props: { userId, permissions: scope }
};
}
});
export default {
async fetch(request: Request, env: Env): Promise<Response> {
return oauthProvider.handleRequest(request, {
'/api/protected': async (request) => {
// Access authenticated user data
const { username } = this.ctx.props;
return new Response(`Hello, ${username}!`);
},
'/oauth/authorize': 'authorize',
'/oauth/token': 'token',
'/oauth/revoke': 'revoke'
});
}
};
Workers KV Setup
Configure your wrangler.toml:
[[kv_namespaces]]
binding = "OAUTH_KV"
id = "your-kv-namespace-id"
Advanced Configuration
Token Exchange Callbacks
Customize token behavior during exchanges:
new OAuthProvider({
// ... other options
tokenExchangeCallback: async (options) => {
if (options.grantType === 'authorization_code') {
// Perform upstream token exchange
const upstreamTokens = await exchangeUpstreamToken(options.props.code);
return {
accessTokenProps: {
...options.props,
upstreamAccessToken: upstreamTokens.access_token
},
newProps: {
...options.props,
upstreamRefreshToken: upstreamTokens.refresh_token
}
};
}
}
});
Custom Error Handling
Implement custom error responses and monitoring:
new OAuthProvider({
// ... other options
onError: ({ code, description, status, headers }) => {
// Log to monitoring service
console.error(`OAuth Error: ${status} ${code} - ${description}`);
// Custom error response
if (code === 'unsupported_grant_type') {
return new Response('Custom error message', { status, headers });
}
}
});
Storage Schema
The library uses a carefully designed storage schema with several security considerations:
🔒 Security Features
- Hash-Only Secrets: Access tokens, refresh tokens, and client secrets stored as hashes only
- Encrypted Props: User properties encrypted with token-derived keys
- Metadata Separation: Non-sensitive metadata stored separately for audit purposes
📊 Storage Structure
KV Structure:
├── grant:{grant_id} → Grant metadata
├── access_token:{token_hash} → Access token info
├── refresh_token:{token_hash} → Refresh token info
├── auth_code:{code_hash} → Authorization code info
└── client:{client_id} → Client configuration
Use Cases
🏢 Enterprise Applications
- Internal APIs: Secure employee access to company resources
- B2B Integrations: Partner API access with granular permissions
- Microservices: Service-to-service authentication
🌐 Public APIs
- Third-Party Integrations: Enable external developers to access your APIs
- Mobile Applications: Secure mobile app authentication
- Web Applications: Standard OAuth flows for web apps
🔧 Developer Tools
- CI/CD Pipelines: Secure automated deployment access
- Monitoring Systems: Authenticated metric collection
- Admin Dashboards: Role-based administrative interfaces
Implementation Benefits
🚀 Performance Advantages
- Edge Computing: Sub-100ms global response times
- Automatic Scaling: Handles traffic spikes without configuration
- Cost Efficiency: Pay-per-request pricing model
🛡️ Security Benefits
- Zero Trust Architecture: Every request authenticated and authorized
- Compliance Ready: Meets OAuth 2.1 security requirements
- Audit Trail: Comprehensive logging and monitoring capabilities
👨💻 Developer Benefits
- TypeScript Support: Full type safety and IDE integration
- Minimal Setup: Production-ready with minimal configuration
- Extensive Documentation: Comprehensive API reference and examples
Advanced Features
Multi-Tenant Support
const oauthProvider = new OAuthProvider({
lookupClient: async (clientId: string) => {
// Multi-tenant client lookup
const [tenantId, appId] = clientId.split(':');
return await getTenantClientConfig(tenantId, appId);
}
});
Custom Scopes and Permissions
const oauthProvider = new OAuthProvider({
onAuthorize: async (request, { clientId, userId, scope }) => {
// Custom scope validation
const userPermissions = await getUserPermissions(userId);
const allowedScopes = scope.filter(s => userPermissions.includes(s));
return {
allow: allowedScopes.length > 0,
props: { userId, permissions: allowedScopes }
};
}
});
Best Practices
🔐 Security Recommendations
- Use strong client secrets and rotate them regularly
- Implement proper scope validation in your authorization handler
- Monitor and log all OAuth activities for security auditing
- Use HTTPS for all OAuth endpoints
📈 Performance Optimization
- Cache client configurations when possible
- Implement efficient user lookup mechanisms
- Use appropriate token TTLs for your use case
- Monitor KV storage usage and costs
🧪 Testing Strategy
- Test all OAuth flows (authorization code, refresh token, etc.)
- Validate error handling for edge cases
- Load test with realistic traffic patterns
- Implement integration tests with real clients
Migration Guide
From Other OAuth Libraries
The library provides compatibility helpers for migrating from other OAuth implementations:
// Migration helper for existing token stores
const migrationHelper = {
async migrateTokens(existingTokens) {
for (const token of existingTokens) {
await oauthProvider.helpers.createGrant({
userId: token.userId,
clientId: token.clientId,
scope: token.scope,
props: token.metadata
});
}
}
};
AI-Assisted Development
This library was largely developed with assistance from Claude AI, demonstrating the potential of AI-assisted development when properly supervised and reviewed by security experts. Every line of code was thoroughly audited and cross-referenced with OAuth specifications.
Support & Resources
- GitHub Issues: Report bugs and request features
- Documentation: Comprehensive API reference
- Storage Schema: Detailed storage documentation
- Security Policy: Security guidelines and reporting
Related Projects
- Cloudflare Workers - Serverless platform
- Workers KV - Edge storage
- OAuth 2.1 Specification - Protocol specification
License
This project is licensed under the MIT License - see the LICENSE file for details.
Secure your APIs with enterprise-grade OAuth 2.1 on Cloudflare’s global edge network 🔐