AuthProvider
Unified authentication provider that dynamically selects the appropriate auth provider based on the provider parameter.
Constructor
new AuthProvider(provider: string, config?: any)
Authentication provider type. Supported values:
'cognito' - AWS Cognito
'auth0' - Auth0
'clerk' - Clerk
'firebase' - Firebase
'leanmcp' - LeanMCP cloud (with user secrets support)
Provider-specific configuration object (see provider-specific docs)
Methods
init()
Initialize the selected auth provider.
await authProvider.init(config?: any): Promise<void>
Optional configuration to override constructor config
verifyToken()
Verify if a token is valid.
await authProvider.verifyToken(token: string): Promise<boolean>
Returns true if token is valid, throws error otherwise
getUser()
Get user information from a token.
await authProvider.getUser(token: string): Promise<any>
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>
Username (required for Cognito)
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>>
Project ID to fetch secrets for
Object with user’s environment variables. Returns empty object for non-LeanMCP providers.
getProviderType()
Get the provider type.
authProvider.getProviderType(): 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
No token provided in request
Token is invalid or expired
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;
}
}
}