Python Keycloak Client

7.1.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

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.")

view raw JSON →