Skip to main content

Keycloak Integration Guide

Complete guide to production-ready authentication with Keycloak for MCP Server with LangGraph.

Table of Contents


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 with FF_ prefix:

Programmatic Configuration


User Provider Pattern

The User Provider pattern enables pluggable authentication backends without changing application code.

Interface

All providers implement the UserProvider abstract base class:

Factory Function

Use create_user_provider() to switch providers:

Switching Providers

Development β†’ Production Migration:

Authentication Flows

1. Resource Owner Password Credentials (ROPC)

When to use: Direct username/password authentication

2. Token Verification (JWKS)

When to use: Verify tokens from other services

3. Token Refresh

When to use: Extend session without re-authentication

4. User Information

When to use: Get detailed user profile

Token Management

Token Lifecycle

JWKS Caching

To minimize HTTP calls to Keycloak:
Benefits:
  • 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, modify sync_user_to_openfga():

Troubleshooting

Common Issues

1. β€œClient secret required”

Problem: Keycloak authentication fails Cause: Missing or incorrect KEYCLOAK_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_id matches 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:
Note: The GHCR optimized image (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 database

3. 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

  1. Complete Setup: Run make setup-keycloak and configure .env
  2. Test Integration: Run python examples/keycloak_usage.py
  3. Customize Roles: Modify role mapping in sync_user_to_openfga()
  4. Production Deploy: Follow Production Deployment Guide
  5. Monitor & Alert: Set up Grafana dashboards and alerts

Need Help?