Registry / auth-security / python-keycloak

python-keycloak

JSON →
library7.1.1pypypi✓ verified 27d ago

python-keycloak is a Python package providing access to the Keycloak API, acting as a client for OpenID Connect and OAuth2 workflows. It is currently at version 7.1.1 and receives regular updates, typically aligning with Keycloak's own release cycles for compatibility and feature support.

pip install python-keycloak
INSTALL
IMPORT
SIG · PYTHON-KEYCLOAK
P
python-keycloak
auth-securitypythonv7.1.1
Install
4.5s avg
Import
894ms
Disk
44MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
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
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.932s · 44.8MB
glibc
py 3.103.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.")
Debug
Known issues
breakingThe `KeycloakAdmin` client's constructor significantly changed between versions 6.x and 7.x. Previously, it could accept a `KeycloakOpenID` object; now, it requires direct configuration parameters such as `server_url`, `realm_name`, `username`, `password`, `client_id`, and `client_secret_key`.
fix
Review the official documentation for `KeycloakAdmin` initialization in version 7.x. Update your `KeycloakAdmin` constructor calls to provide all necessary direct configuration parameters instead of passing a `KeycloakOpenID` instance.
affects: 7.0.0 and above
gotchaSSL certificate verification is enabled by default (`verify_ssl_cert=True`). This will cause connection errors with self-signed certificates or development setups that don't use valid CA-signed certificates.
fix
For development or testing with self-signed certificates, explicitly set `verify_ssl_cert=False` in the `KeycloakOpenID` or `KeycloakAdmin` constructor. Always re-enable `verify_ssl_cert=True` for production deployments.
affects: All versions
gotchaConfusing 'client_secret_key' parameter behavior for confidential clients. If your Keycloak client is confidential, you MUST provide `client_secret_key` during initialization. Public clients (e.g., SPA, mobile apps) should omit this parameter, and its presence can lead to authentication failures.
fix
Ensure `client_secret_key` is passed to `KeycloakOpenID` or `KeycloakAdmin` constructors ONLY if your Keycloak client is configured as 'confidential'. For public clients, ensure this parameter is omitted or set to `None`.
affects: All versions
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.
fix
Ensure 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'.
fix
Verify 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.
fix
Install 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.
fix
Use 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.
Agent activity
13 hits · last 30 days
node
8
OpenAI (training)
1
Resources
python-keycloak — pip install python-keycloak · libregistry