Skip to main content

AuthProvider

Unified authentication provider that dynamically selects the appropriate auth provider based on the provider parameter.

Constructor

new AuthProvider(provider: string, config?: any)
provider
string
required
Authentication provider type. Supported values:
  • 'cognito' - AWS Cognito
  • 'auth0' - Auth0
  • 'clerk' - Clerk
  • 'firebase' - Firebase
  • 'leanmcp' - LeanMCP cloud (with user secrets support)
config
object
Provider-specific configuration object (see provider-specific docs)

Methods

init()

Initialize the selected auth provider.
await authProvider.init(config?: any): Promise<void>
config
object
Optional configuration to override constructor config

verifyToken()

Verify if a token is valid.
await authProvider.verifyToken(token: string): Promise<boolean>
token
string
required
JWT token to verify
result
boolean
Returns true if token is valid, throws error otherwise

getUser()

Get user information from a token.
await authProvider.getUser(token: string): Promise<any>
token
string
required
JWT token to decode
user
object
User object with provider-specific fields. Common fields:
  • sub - User ID
  • email - Email address
  • email_verified - Email verification status
  • attributes - Full decoded token payload

refreshToken()

Refresh an authentication token.
await authProvider.refreshToken(refreshToken: string, username?: string): Promise<any>
refreshToken
string
required
Refresh token
username
string
Username (required for Cognito)
tokens
object
New access token and optionally new refresh token

getUserSecrets()

Get user secrets for a project (LeanMCP provider only).
await authProvider.getUserSecrets(token: string, projectId: string): Promise<Record<string, string>>
token
string
required
JWT token
projectId
string
required
Project ID to fetch secrets for
secrets
Record<string, string>
Object with user’s environment variables. Returns empty object for non-LeanMCP providers.

getProviderType()

Get the provider type.
authProvider.getProviderType(): string
type
string
Returns the provider type (e.g., ‘cognito’, ‘auth0’, ‘clerk’)

Example Usage

import { AuthProvider } from '@leanmcp/auth';

// Initialize with Cognito
const authProvider = new AuthProvider('cognito', {
  region: 'us-east-1',
  userPoolId: 'us-east-1_ABC123',
  clientId: 'your-client-id',
});

await authProvider.init();

// Verify token
try {
  await authProvider.verifyToken(token);
  console.log('Token is valid');
} catch (error) {
  console.error('Invalid token:', error);
}

// Get user info
const user = await authProvider.getUser(token);
console.log('User:', user.email);

AuthProviderBase

Abstract base class for implementing custom authentication providers.

Abstract Methods

Extend this class and implement these methods:
abstract class AuthProviderBase {
  abstract init(config?: any): Promise<void>;
  abstract refreshToken(refreshToken: string, username?: string): Promise<any>;
  abstract verifyToken(token: string): Promise<boolean>;
  abstract getUser(token: string): Promise<any>;
}

Custom Provider Example

import { AuthProviderBase } from '@leanmcp/auth';

export class CustomAuthProvider extends AuthProviderBase {
  private apiKey: string = '';

  async init(config?: { apiKey?: string }): Promise<void> {
    this.apiKey = config?.apiKey || process.env.CUSTOM_API_KEY || '';
    if (!this.apiKey) {
      throw new Error('API key is required');
    }
  }

  async verifyToken(token: string): Promise<boolean> {
    // Implement your verification logic
    const response = await fetch('https://your-api.com/verify', {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.ok;
  }

  async getUser(token: string): Promise<any> {
    // Implement your user fetching logic
    const response = await fetch('https://your-api.com/user', {
      headers: { Authorization: `Bearer ${token}` },
    });
    return await response.json();
  }

  async refreshToken(refreshToken: string): Promise<any> {
    // Implement your refresh logic
    const response = await fetch('https://your-api.com/refresh', {
      method: 'POST',
      body: JSON.stringify({ refresh_token: refreshToken }),
    });
    return await response.json();
  }
}

Error Handling

AuthenticationError

All authentication errors are thrown as AuthenticationError instances:
class AuthenticationError extends Error {
  constructor(message: string, code: string);
  code: string;
}

Error Codes

MISSING_TOKEN
string
No token provided in request
INVALID_TOKEN
string
Token is invalid or expired
VERIFICATION_FAILED
string
Token verification failed (network error, etc.)

Example Error Handling

import { AuthenticationError } from '@leanmcp/auth';

try {
  await authProvider.verifyToken(token);
} catch (error) {
  if (error instanceof AuthenticationError) {
    switch (error.code) {
      case 'MISSING_TOKEN':
        console.error('No token provided');
        break;
      case 'INVALID_TOKEN':
        console.error('Token expired or invalid');
        break;
      case 'VERIFICATION_FAILED':
        console.error('Verification error:', error.message);
        break;
    }
  }
}

Build docs developers (and LLMs) love