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
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
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
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:ghcr.io/vishnu2kmohan/keycloak-optimized:26.4.2) is built via GitHub Actions from docker/Dockerfile.keycloak. It pre-compiles Quarkus, enabling --optimized mode and readOnlyRootFilesystem: true for enhanced security.
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?