Python Keycloak Client
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.
Warnings
- breaking The `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`.
- gotcha SSL 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.
- gotcha Confusing '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.
Install
-
pip install python-keycloak
Imports
- KeycloakOpenID
from keycloak import KeycloakOpenID
- KeycloakAdmin
from keycloak.admin import KeycloakAdmin
Quickstart
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.")