OAuth 2.1 Authentication Template
The typescript-oauth template provides a complete, production-ready OAuth 2.1 implementation for your MCP server. Perfect for user-facing applications that need industry-standard authentication.
๐ฏ What This Template Provides
- โ OAuth 2.1 Implementation - Complete, standards-compliant
- โ Dual Transport - STDIO for MCP + HTTP for OAuth metadata
- โ Token Validation - Automatic JWT verification, audience binding
- โ Scope-Based Access - Fine-grained permissions
- โ Working Example Tools - Public, protected, and scoped tools
- โ Studio Integration - Complete OAuth flow in NitroStack Studio
- โ Multi-Provider Support - Works with Auth0, Okta, Keycloak, etc.
๐ Quick Start (5 Minutes)
1. Create Project
npx nitrostack init my-oauth-server
# Select: typescript-oauth
cd my-oauth-server
npm install
2. Setup Auth0
See the complete setup guide or follow these quick steps:
Create Auth0 Application:
- Auth0 Dashboard โ Applications โ Create
- Type: Regular Web Application
- Callback URLs:
http://localhost:3000/auth/callback - Copy Client ID & Secret
Create Auth0 API:
- Auth0 Dashboard โ APIs โ Create
- Identifier:
http://localhost:3002 - Add scopes:
read,write,admin
3. Configure Environment
Edit .env:
RESOURCE_URI=http://localhost:3002
AUTH_SERVER_URL=https://YOUR-TENANT.auth0.com
TOKEN_AUDIENCE=http://localhost:3002
TOKEN_ISSUER=https://YOUR-TENANT.auth0.com/
4. Start & Test
npm run dev
Then in NitroStack Studio:
- Auth โ OAuth 2.1
- Discover:
http://localhost:3002 - Enter Client ID/Secret
- Start OAuth Flow
- Test tools! โ
๐๏ธ Project Structure
typescript-oauth/
โโโ src/
โ โโโ guards/
โ โ โโโ oauth.guard.ts # OAuth token validation
โ โโโ modules/demo/
โ โ โโโ demo.module.ts
โ โ โโโ demo.tools.ts # Example tools
โ โโโ app.module.ts # OAuthModule configuration
โ โโโ index.ts # Entry point
โโโ .env # Environment config
โโโ OAUTH_SETUP.md # Complete setup guide
โโโ README.md
๐ Example Tools
Public Tool (No Auth)
@Tool({
name: 'get_server_info',
description: 'Get public server information',
})
async getServerInfo() {
return {
name: 'My OAuth Server',
version: '1.0.0',
};
}
Protected Tool (OAuth Required)
@Tool({
name: 'get_user_profile',
description: 'Get authenticated user profile',
})
@UseGuards(OAuthGuard)
async getUserProfile(@ExecutionContext() context: ExecutionContext) {
return {
user: context.auth.subject, // 'auth0|abc123'
scopes: context.auth.scopes, // ['read', 'write']
email: context.auth.claims.email,
};
}
Scoped Tool (Requires Specific Scope)
@Tool({
name: 'admin_statistics',
description: 'Get admin statistics',
})
@UseGuards(OAuthGuard, createScopeGuard('read', 'admin'))
async adminStats() {
// Only accessible with both 'read' AND 'admin' scopes
return { stats: { ... } };
}
๐ How OAuth Works in This Template
Dual Transport Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Your OAuth 2.1 MCP Server โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ ๐ก STDIO Transport โ
โ โโ MCP Protocol Communication โ
โ โโ Tool Execution โ
โ โโ Connected to Studio/Claude โ
โ โ
โ ๐ HTTP Server (Port 3002) โ
โ โโ OAuth Metadata Endpoints โ
โ โโ /.well-known/oauth-protected- โ
โ โ resource (RFC 9728) โ
โ โโ Token Validation โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Key Benefits:
- โ Fast STDIO for MCP protocol
- โ Standards-compliant HTTP for OAuth
- โ Automatic - no manual configuration needed!
OAuth Flow
- Discovery - Studio fetches OAuth metadata from your server
- Credentials - You enter Client ID/Secret
- Authorization - Redirected to Auth0 login
- Token Exchange - Auth code exchanged for JWT token
- Tool Calls - Token automatically included in requests
๐ง Configuration
OAuthModule Setup
// src/app.module.ts
OAuthModule.forRoot({
// Your MCP server URL
resourceUri: process.env.RESOURCE_URI!,
// Your OAuth provider(s)
authorizationServers: [process.env.AUTH_SERVER_URL!],
// Supported scopes
scopesSupported: ['read', 'write', 'admin'],
// Optional: Token validation
audience: process.env.TOKEN_AUDIENCE,
issuer: process.env.TOKEN_ISSUER,
// Optional: Custom validation
customValidation: async (tokenPayload) => {
// Add your own validation logic
return true;
},
})
Protecting Tools
import { Tool, UseGuards, OAuthGuard, createScopeGuard } from 'nitrostack';
// Requires valid OAuth token
@UseGuards(OAuthGuard)
// Requires specific scope(s)
@UseGuards(OAuthGuard, createScopeGuard('read'))
// Requires multiple scopes
@UseGuards(OAuthGuard, createScopeGuard('read', 'admin'))
๐งช Testing in Studio
Complete Flow
-
Start Server:
npm run dev -
Open Studio: Navigate to
http://localhost:3000 -
Discover OAuth Server:
- Auth โ OAuth 2.1 tab
- Enter:
http://localhost:3002 - Click "Discover Auth Config"
- โ Should show discovered metadata
-
Enter Credentials:
- Client ID:
[Your Auth0 Client ID] - Client Secret:
[Your Auth0 Client Secret] - Click "Save Client Credentials"
- Client ID:
-
Start OAuth Flow:
- Click "Start Authorization Flow"
- Login to Auth0
- Authorize the application
- โ Redirected back with JWT token!
-
Test Tools:
- Go to Tools tab
- Execute any protected tool
- โ Token automatically included!
๐ Security Features
1. Token Audience Binding (RFC 8707)
Tokens are validated to ensure they were issued specifically for your MCP server:
// Token must have your RESOURCE_URI in audience claim
{
"aud": "http://localhost:3002", // โ Must match
"sub": "user123",
"scope": "read write admin"
}
2. Automatic Token Validation
NitroStack automatically validates:
- โ JWT signature (verified against JWKS)
- โ Token expiration (exp claim)
- โ Token audience (aud claim)
- โ Token issuer (iss claim)
- โ Not before time (nbf claim)
- โ Required scopes
3. Short-Lived Tokens
Configure Auth0 for short-lived tokens:
- Access Token: 1 hour
- Refresh Token: 30 days
Studio automatically handles token refresh.
๐ Production Deployment
1. Update Environment Variables
# Production URLs (with HTTPS!)
RESOURCE_URI=https://mcp.yourapp.com
AUTH_SERVER_URL=https://auth.yourapp.com
TOKEN_AUDIENCE=https://mcp.yourapp.com
TOKEN_ISSUER=https://auth.yourapp.com/
2. Configure OAuth Provider
Update your Auth0 application:
- Allowed Callback URLs:
https://studio.yourapp.com/auth/callback - Allowed Web Origins:
https://studio.yourapp.com
3. Deploy
# Build
npm run build
# Deploy to your platform
# (Heroku, AWS, GCP, Azure, etc.)
๐ Supported OAuth Providers
This template works with any OAuth 2.1 compliant provider:
- โ Auth0 - Easiest for testing
- โ Okta - Enterprise-ready
- โ Keycloak - Self-hosted
- โ Azure AD / Entra ID
- โ Google Identity Platform
- โ AWS Cognito
See OAUTH_SETUP.md for provider-specific configuration.
๐ Learn More
- Complete Setup Guide - Step-by-step Auth0 setup
- OAuth 2.1 SDK Guide - Comprehensive OAuth documentation
- Authentication Overview - All auth methods
- Template README - Template-specific docs
๐ก Common Use Cases
User-Facing Applications
Perfect for applications where users login with their own accounts:
- Dashboard applications
- Admin panels
- Content management systems
- SaaS platforms
Multi-Tenant Applications
@Tool({ name: 'get_tenant_data' })
@UseGuards(OAuthGuard)
async getTenantData(@ExecutionContext() context: ExecutionContext) {
const tenantId = context.auth.claims.tenant_id;
return await db.data.find({ tenantId });
}
Role-Based Access Control
@Tool({ name: 'admin_panel' })
@UseGuards(OAuthGuard, createScopeGuard('admin'))
async adminPanel(@ExecutionContext() context: ExecutionContext) {
// Only users with 'admin' scope can access
}
๐ Why This Template is Amazing
Traditional OAuth Implementation โ
Complexity:
- 500+ lines of boilerplate
- Manual JWKS fetching & caching
- Token validation logic
- Metadata endpoints
- Security pitfalls everywhere
Time: 2-3 days
This Template โ
Simplicity:
OAuthModule.forRoot({ ... });
@UseGuards(OAuthGuard)
Time: 5 minutes!
You Get:
- โ Production-grade OAuth implementation
- โ Standards-compliant (all RFCs)
- โ Secure by default
- โ Working examples
- โ Complete testing flow
Next Steps:
- Create your project with
npx nitrostack init - Follow the setup guide
- Test in Studio
- Customize for your needs
- Deploy to production!
Happy coding! ๐