|
| 1 | +""" |
| 2 | +Keycloak authentication helpers for MCP agents. |
| 3 | +
|
| 4 | +Provides OAuth2 client credentials flow authentication via Keycloak's |
| 5 | +Dynamic Client Registration (DCR) endpoint. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + from keycloak_auth import get_auth_headers |
| 9 | +
|
| 10 | + headers = await get_auth_headers(keycloak_realm_url) |
| 11 | + # Returns {"Authorization": "Bearer <token>"} or None if no URL provided |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import logging |
| 17 | +from datetime import datetime |
| 18 | + |
| 19 | +import httpx |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +async def register_client_via_dcr(keycloak_realm_url: str, client_name_prefix: str = "agent") -> tuple[str, str]: |
| 25 | + """ |
| 26 | + Register a new client dynamically using Keycloak's DCR endpoint. |
| 27 | +
|
| 28 | + Args: |
| 29 | + keycloak_realm_url: The Keycloak realm URL (e.g., http://localhost:8080/realms/myrealm) |
| 30 | + client_name_prefix: Prefix for the generated client name |
| 31 | +
|
| 32 | + Returns: |
| 33 | + Tuple of (client_id, client_secret) |
| 34 | +
|
| 35 | + Raises: |
| 36 | + RuntimeError: If DCR registration fails |
| 37 | + """ |
| 38 | + dcr_url = f"{keycloak_realm_url}/clients-registrations/openid-connect" |
| 39 | + logger.info("📝 Registering client via DCR...") |
| 40 | + |
| 41 | + async with httpx.AsyncClient() as http_client: |
| 42 | + response = await http_client.post( |
| 43 | + dcr_url, |
| 44 | + json={ |
| 45 | + "client_name": f"{client_name_prefix}-{datetime.now().strftime('%Y%m%d-%H%M%S')}", |
| 46 | + "grant_types": ["client_credentials"], |
| 47 | + "token_endpoint_auth_method": "client_secret_basic", |
| 48 | + }, |
| 49 | + headers={"Content-Type": "application/json"}, |
| 50 | + ) |
| 51 | + |
| 52 | + if response.status_code not in (200, 201): |
| 53 | + raise RuntimeError( |
| 54 | + f"DCR registration failed at {dcr_url}: status={response.status_code}, response={response.text}" |
| 55 | + ) |
| 56 | + |
| 57 | + data = response.json() |
| 58 | + logger.info(f"✅ Registered client: {data['client_id'][:20]}...") |
| 59 | + return data["client_id"], data["client_secret"] |
| 60 | + |
| 61 | + |
| 62 | +async def get_keycloak_token(keycloak_realm_url: str, client_id: str, client_secret: str) -> str: |
| 63 | + """ |
| 64 | + Get an access token from Keycloak using client_credentials grant. |
| 65 | +
|
| 66 | + Args: |
| 67 | + keycloak_realm_url: The Keycloak realm URL |
| 68 | + client_id: The OAuth client ID |
| 69 | + client_secret: The OAuth client secret |
| 70 | +
|
| 71 | + Returns: |
| 72 | + The access token string |
| 73 | +
|
| 74 | + Raises: |
| 75 | + RuntimeError: If token request fails |
| 76 | + """ |
| 77 | + token_url = f"{keycloak_realm_url}/protocol/openid-connect/token" |
| 78 | + logger.info("🔑 Getting access token from Keycloak...") |
| 79 | + |
| 80 | + async with httpx.AsyncClient() as http_client: |
| 81 | + response = await http_client.post( |
| 82 | + token_url, |
| 83 | + data={ |
| 84 | + "grant_type": "client_credentials", |
| 85 | + "client_id": client_id, |
| 86 | + "client_secret": client_secret, |
| 87 | + }, |
| 88 | + headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 89 | + ) |
| 90 | + |
| 91 | + if response.status_code != 200: |
| 92 | + raise RuntimeError( |
| 93 | + f"Token request failed at {token_url}: status={response.status_code}, response={response.text}" |
| 94 | + ) |
| 95 | + |
| 96 | + token_data = response.json() |
| 97 | + logger.info(f"✅ Got access token (expires in {token_data.get('expires_in', '?')}s)") |
| 98 | + return token_data["access_token"] |
| 99 | + |
| 100 | + |
| 101 | +async def get_auth_headers(keycloak_realm_url: str | None, client_name_prefix: str = "agent") -> dict[str, str] | None: |
| 102 | + """ |
| 103 | + Get authorization headers if Keycloak is configured. |
| 104 | +
|
| 105 | + This is the main entry point for agents that need OAuth authentication. |
| 106 | + It handles the full flow: DCR registration -> token acquisition -> headers. |
| 107 | +
|
| 108 | + Args: |
| 109 | + keycloak_realm_url: The Keycloak realm URL, or None to skip auth |
| 110 | + client_name_prefix: Prefix for the dynamically registered client name |
| 111 | +
|
| 112 | + Returns: |
| 113 | + {"Authorization": "Bearer <token>"} if keycloak_realm_url is set, None otherwise |
| 114 | + """ |
| 115 | + if not keycloak_realm_url: |
| 116 | + return None |
| 117 | + |
| 118 | + client_id, client_secret = await register_client_via_dcr(keycloak_realm_url, client_name_prefix) |
| 119 | + access_token = await get_keycloak_token(keycloak_realm_url, client_id, client_secret) |
| 120 | + return {"Authorization": f"Bearer {access_token}"} |
0 commit comments