Install & Compatibility
Where this runs
tested against v7.1.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.932s · 44.8MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 4.5s · import 0.856s · 45MB
44MB installed
● package 44MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
KeycloakOpenID
✓ from keycloak import KeycloakOpenID
KeycloakAdmin
✓ from keycloak.admin import KeycloakAdmin
Demonstrates how to initialize the `KeycloakOpenID` client, obtain an access token using the Direct Access Grant (Resource Owner Password Credentials) flow, decode the token, and refresh it. Remember to configure your Keycloak server with a realm, client, and user. Set `verify_ssl_cert=True` in production environments.
import os
from keycloak import KeycloakOpenID
# Configuration from environment variables or sensible defaults
KEYCLOAK_SERVER_URL = os.environ.get('KEYCLOAK_SERVER_URL', 'http://localhost:8080/')
KEYCLOAK_REALM_NAME = os.environ.get('KEYCLOAK_REALM_NAME', 'myrealm')
KEYCLOAK_CLIENT_ID = os.environ.get('KEYCLOAK_CLIENT_ID', 'my-client-id')
KEYCLOAK_CLIENT_SECRET = os.environ.get('KEYCLOAK_CLIENT_SECRET', '') # Required for confidential clients
KEYCLOAK_USERNAME = os.environ.get('KEYCLOAK_USERNAME', 'testuser')
KEYCLOAK_PASSWORD = os.environ.get('KEYCLOAK_PASSWORD', 'password')
# Initialize KeycloakOpenID client
keycloak_openid = KeycloakOpenID(
server_url=KEYCLOAK_SERVER_URL,
realm_name=KEYCLOAK_REALM_NAME,
client_id=KEYCLOAK_CLIENT_ID,
client_secret_key=KEYCLOAK_CLIENT_SECRET, # Pass if client is confidential, otherwise omit
verify_ssl_cert=False # Set to True for production, False for dev/self-signed certs
)
try:
# Get initial tokens using Direct Access Grant (Resource Owner Password Credentials Flow)
# Note: This flow is generally not recommended for public clients (e.g., browser-based apps)
# and should be used cautiously, primarily for trusted backend services or CLI tools.
token = keycloak_openid.token(KEYCLOAK_USERNAME, KEYCLOAK_PASSWORD)
print("Successfully obtained token:")
print(f" Access Token (first 10 chars): {token.get('access_token', '')[:10]}...")
print(f" Refresh Token (first 10 chars): {token.get('refresh_token', '')[:10]}...")
print(f" Expires in: {token.get('expires_in')}s")
# Example: Verify token
decoded_token = keycloak_openid.decode_token(token['access_token'])
print(f" Decoded Access Token Subject: {decoded_token.get('sub')}")
# Example: Refresh token
if 'refresh_token' in token and token['refresh_token']:
print("\nAttempting to refresh token...")
refreshed_token = keycloak_openid.refresh_token(token['refresh_token'])
print("Successfully refreshed token:")
print(f" New Access Token (first 10 chars): {refreshed_token.get('access_token', '')[:10]}...")
print(f" New Expires in: {refreshed_token.get('expires_in')}s")
else:
print("No refresh token available or provided.")
except Exception as e:
print(f"Error during Keycloak interaction: {e}")
print("Please ensure Keycloak is running, the realm, client ID/secret, and user credentials are correct.")
print("Also, verify 'Direct Access Grants' is enabled for the client in Keycloak's client settings.")
Errors
Common errors & fixes
KeycloakGetOpenIDConfigurationError: Failed to get the OpenID Connect configuration from Keycloak
The `KeycloakOpenID` client failed to retrieve the OpenID Connect configuration from the Keycloak server, usually due to incorrect server URL, realm name, or network connectivity issues.
fixEnsure the `server_url` and `realm_name` are precisely correct and accessible, and that the Keycloak server is running and configured properly.
KeycloakAuthenticationError: {"error":"invalid_grant","error_description":"Invalid user credentials"}
The provided username or password for authentication via `keycloak_openid.token()` is incorrect, or the Keycloak client is not configured to allow 'Direct Access Grants'.
fixVerify the username and password are correct. If using the password grant type, ensure the Keycloak client has 'Direct Access Grants Enabled' turned on in its Keycloak settings.
ModuleNotFoundError: No module named 'keycloak'
The `python-keycloak` package has not been installed in the Python environment, or the script is being run in a different environment than where the package was installed.
fixInstall the package using pip: `pip install python-keycloak`.
AttributeError: 'KeycloakOpenID' object has no attribute 'get_users'
The `KeycloakOpenID` client is designed for OpenID Connect flows (authentication, token management) and does not provide administrative functions like managing users. Administrative tasks require the `KeycloakAdmin` client.
fixUse the `KeycloakAdmin` client for administrative operations such as `get_users`. Ensure you import `KeycloakAdmin` and initialize it with appropriate admin credentials and client settings.
Upgrade
Version history
7.1.1latest on PyPI · released Feb 15, 2026
Audit
Dependencies
requestsrequiredHTTP client for API interactions.
pyjwt[crypto]requiredJSON Web Token (JWT) handling, including cryptographic operations.
requests-toolbeltrequiredProvides various utilities for the requests library, such as multipart/form-data encoding.