@Authenticated decorator and multiple auth providers.
Overview
LeanMCP’s authentication system provides:- Simple decorator-based protection - Add
@Authenticatedto methods or classes - Multi-provider support - Auth0, Clerk, AWS Cognito, Firebase, LeanMCP
- Automatic user injection - Access
authUserin protected methods - Concurrency safe - Uses AsyncLocalStorage for request isolation
- MCP protocol compliant - Tokens passed via
_meta.authorization
Installation
Install the auth package:Auth0 Integration
Clerk Integration
AWS Cognito Integration
Firebase Integration
The authUser Variable
When using@Authenticated, a global authUser variable is automatically available in your methods:
Provider-Specific User Data
Auth0:Authentication Options
Skip User Fetch
For better performance when you only need token validation:Class vs Method Level
Protect entire service:Error Handling
Handle authentication errors gracefully:Client Integration
Clients pass tokens via the_meta field:
Best Practices
Security
- Always use HTTPS in production
- Store tokens securely (keychain, encrypted storage)
- Implement token refresh before expiration
- Add rate limiting to protect against brute force
- Never log or expose tokens in error messages
Configuration
- Use environment variables for credentials
- Never hardcode secrets in code
- Use
_metafor auth, not business arguments - Validate environment variables at startup
Performance
- Use
getUser: falsewhen you only need token validation - JWKS keys are cached automatically
- Consider caching user data for repeated calls
Troubleshooting
Token Not Being Recognized
Problem:MISSING_TOKEN error even when passing token.
Solutions:
- Ensure token is in
_meta.authorization.token - Check authorization type is
'bearer' - Verify token format (should be JWT string)
Token Verification Fails
Problem:INVALID_TOKEN or VERIFICATION_FAILED errors.
Solutions:
- Verify token hasn’t expired
- Check provider configuration (domain, client ID, etc.)
- Ensure provider is initialized with
await authProvider.init() - Verify audience matches in Auth0/Cognito
authUser is Undefined
Problem:authUser variable is undefined in protected methods.
Solutions:
- Ensure
getUseroption is not set tofalse - Check that
@Authenticateddecorator is applied - Verify the decorator is from
@leanmcp/auth - Check provider supports user info endpoint
Next Steps
Schema Design
Design robust validation schemas
Error Handling
Handle authentication and validation errors
Deployment
Deploy authenticated services to production
API Reference
Complete auth API documentation