Keycloak Integration Guide
Complete guide to production-ready authentication with Keycloak for MCP Server with LangGraph.Table of Contents
- Overview
- Quick Start
- Architecture
- Configuration
- User Provider Pattern
- Authentication Flows
- Token Management
- Role Mapping
- Troubleshooting
- Production Best Practices
Overview
Keycloak integration provides production-grade authentication for your MCP server:Key Features
- ✅ OAuth2/OIDC Compliance: Industry-standard authentication protocols
- ✅ JWKS Token Verification: No shared secrets, uses public key cryptography
- ✅ Automatic Token Refresh: Seamless session extension without re-authentication
- ✅ Role Synchronization: Automatic mapping of Keycloak roles/groups to OpenFGA
- ✅ User Provider Pattern: Pluggable architecture supporting multiple backends
- ✅ Backward Compatible: Defaults to in-memory provider for development
When to Use
| Environment | Provider | Use Case |
|---|---|---|
| Development | InMemory | Local testing, no external dependencies |
| Staging | Keycloak | Pre-production validation |
| Production | Keycloak | Enterprise authentication, SSO, compliance |
Quick Start
1. Start Keycloak
2. Initialize Keycloak
3. Configure Environment
Add to.env:
4. Test Authentication
Architecture
Component Overview
Authentication Flow (ROPC)
Token Verification Flow
Configuration
Settings Reference
| Setting | Environment Variable | Default | Description |
|---|---|---|---|
| Provider Type | AUTH_PROVIDER | inmemory | inmemory or keycloak |
| Server URL | KEYCLOAK_SERVER_URL | http://localhost:8180 | Keycloak base URL |
| Realm | KEYCLOAK_REALM | langgraph-agent | Keycloak realm name |
| Client ID | KEYCLOAK_CLIENT_ID | langgraph-client | OAuth2 client ID |
| Client Secret | KEYCLOAK_CLIENT_SECRET | None | OAuth2 client secret (required) |
| Admin Username | KEYCLOAK_ADMIN_USERNAME | admin | Admin API username |
| Admin Password | KEYCLOAK_ADMIN_PASSWORD | None | Admin API password |
| Verify SSL | KEYCLOAK_VERIFY_SSL | true | Verify SSL certificates |
| Timeout | KEYCLOAK_TIMEOUT | 30 | HTTP request timeout (seconds) |
Feature Flags
Control Keycloak features via environment variables withFF_ prefix:
Programmatic Configuration
User Provider Pattern
The User Provider pattern enables pluggable authentication backends without changing application code.Interface
All providers implement theUserProvider abstract base class:
Factory Function
Usecreate_user_provider() to switch providers:
Switching Providers
Development → Production Migration:Authentication Flows
1. Resource Owner Password Credentials (ROPC)
When to use: Direct username/password authentication2. Token Verification (JWKS)
When to use: Verify tokens from other services3. Token Refresh
When to use: Extend session without re-authentication4. User Information
When to use: Get detailed user profileToken Management
Token Lifecycle
JWKS Caching
To minimize HTTP calls to Keycloak:- Reduces latency for token verification
- Decreases load on Keycloak server
- Handles key rotation automatically (refreshes if kid not found)
Token Refresh Strategy
Role Mapping to OpenFGA
Automatic Synchronization
When a user authenticates, their Keycloak roles/groups are automatically synced to OpenFGA:Mapping Examples
| Keycloak | OpenFGA Tuple |
|---|---|
Realm role: admin | user:alice admin system:global |
Group: /acme | user:alice member organization:acme |
Group: /acme/engineering | user:alice member organization:engineering |
Realm role: premium | user:alice assignee role:premium |
Client role: executor | user:alice assignee role:executor |
Custom Mapping
To customize role mapping, modifysync_user_to_openfga():
Troubleshooting
Common Issues
1. “Client secret required”
Problem: Keycloak authentication fails Cause: Missing or incorrectKEYCLOAK_CLIENT_SECRET
Solution:
2. “Connection refused on port 8180”
Problem: Cannot connect to Keycloak Cause: Keycloak not started or still initializing Solution:3. “Token verification failed: kid not found”
Problem: Token signed with unknown key Cause: JWKS cache out of date or key rotation Solution:- TokenValidator automatically refreshes JWKS
- If persistent, check Keycloak realm settings
- Verify
client_idmatches token audience
4. “User not found in admin API”
Problem: User authenticated but admin API lookup fails Cause: Admin credentials incorrect Solution:5. “OpenFGA sync failed”
Problem: Role synchronization errors Cause: OpenFGA not initialized or network issues Solution:Debug Mode
Enable detailed logging:Testing Connectivity
Production Best Practices
Security
1. Use HTTPS in Production
2. Rotate Secrets Regularly
3. Use Infisical for Secret Management
Performance
1. Enable JWKS Caching
- ✅ Already enabled (1-hour TTL)
- ✅ Automatic cache refresh on key rotation
2. Enable Role Sync on Login
3. Connection Pooling
Monitoring
1. Track Authentication Metrics
2. Set Up Alerts
- High authentication failure rate (> 10%)
- Token verification errors (> 5%)
- Keycloak connection failures
- JWKS fetch failures
3. Grafana Dashboards
See:observability/grafana/auth_dashboard.json (coming in Phase 2)
High Availability
1. Keycloak Clustering
For production, deploy Keycloak in clustered mode:2. Database Replication
Use PostgreSQL replication for Keycloak database3. Graceful Degradation
Compliance
1. GDPR Compliance
- Enable Keycloak audit logging
- Configure user data retention policies
- Implement right-to-be-forgotten workflows
2. SOC 2 Requirements
- Enable MFA in Keycloak
- Implement session timeout policies
- Log all authentication events
3. HIPAA Requirements
- Use encrypted connections (TLS 1.3)
- Implement strong password policies
- Enable comprehensive audit logging
Next Steps
- Complete Setup: Run
make setup-keycloakand configure.env - Test Integration: Run
python examples/keycloak_usage.py - Customize Roles: Modify role mapping in
sync_user_to_openfga() - Production Deploy: Follow Production Deployment Guide
- Monitor & Alert: Set up Grafana dashboards and alerts
Related Documentation
Need Help?