Overview of python-keycloak
masterpython-keycloak
python-keycloak is a Python package designed to provide programmatic access to the Keycloak API. It allows developers to interact with Keycloak services using Python code.
repository·master·Indexed 21 days ago
https://github.com/marcospereirampj/python-keycloakA Python client library providing programmatic access to the Keycloak API. It supports OpenID Connect (OIDC) flows for user authentication and authorization, administrative operations via the KeycloakAdmin class for managing users, realms, and clients, and User-Managed Access (UMA) for fine-grained authorization. The library also supports asynchronous operations for non-blocking integration.
python-keycloak is a Python package designed to provide programmatic access to the Keycloak API. It allows developers to interact with Keycloak services using Python code.
The python-keycloak library provides integration for Keycloak using three primary patterns:
Additionally, the library supports asynchronous operations for non-blocking integration.
The project uses tox to manage testing and linting workflows. Note that tox requires docker to be installed on your system, as it spins up a local Keycloak instance for integration testing to avoid excessive mocking.
tests environment.flake8, black, and isort standards using the check environment.isort and black formatting using the apply-check environment (note: flake8 errors must still be fixed manually).docs environment.# Run unit tests
tox -e tests
# Run linting and formatting checks
tox -e check
# Automatically apply formatting (black and isort)
tox -e apply-check
# Check documentation for build warnings
tox -e docsTo interact with Keycloak using OpenID Connect, instantiate the KeycloakOpenID class.
Important Note on server_url: For Keycloak versions older than 18, you must append /auth/ to the end of the server_url.
Common parameters:
server_url: The base URL of your Keycloak server.client_id: The ID of the client configured in Keycloak.realm_name: The name of the realm.client_secret_key: The client secret (required for confidential clients).pool_maxsize: (Optional) Sets the connection pool size.from keycloak import KeycloakOpenID
# Configure client
# For versions older than 18 /auth/ must be added at the end of the server_url.
keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/",
client_id="example_client",
realm_name="example_realm",
client_secret_key="secret",
pool_maxsize=15)If you prefer to install from source, you can clone the repository or download the source code directly from GitHub. Once you have the source code locally, navigate to the root directory and install it into your site-packages using pip:
git clone https://github.com/marcospereirampj/python-keycloak.git
cd python-keycloak
python -m pip install .git clone https://github.com/marcospereirampj/python-keycloak.git
python -m pip install .The KeycloakAdmin class allows you to perform administrative operations like managing users. It requires a KeycloakOpenIDConnection object for authentication.
Setup Steps:
KeycloakOpenIDConnection providing server_url, admin credentials (username, password), realm_name (usually master for admin tasks), and client credentials.KeycloakAdmin(connection=...).Key Operations:
create_user(user_details, exist_ok=True): Creates a new user. You can pass exist_ok=False to raise an exception if the username already exists. You can also include credentials in the user details dictionary to set a password immediately.from keycloak import KeycloakAdmin
from keycloak import KeycloakOpenIDConnection
keycloak_connection = KeycloakOpenIDConnection(
server_url="http://localhost:8080/",
username='example-admin',
password='secret',
realm_name="master",
user_realm_name="only_if_other_realm_than_master",
client_id="my_client",
client_secret_key="client-secret",
verify=True)
keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
# Add user with password
new_user = keycloak_admin.create_user({
"email": "example@example.com",
"username": "example@example.com",
"enabled": True,
"firstName": "Example",
"lastName": "Example",
"credentials": [{"value": "secret", "type": "password"}]
})To use User-Managed Access (UMA) features, initialize a KeycloakUMA instance by passing a configured KeycloakOpenIDConnection object to its connection parameter. The connection object requires server_url, realm_name, client_id, and client_secret_key.
from keycloak import KeycloakOpenIDConnection
from keycloak import KeycloakUMA
keycloak_connection = KeycloakOpenIDConnection(
server_url="http://localhost:8080/",
realm_name="master",
client_id="my_client",
client_secret_key="client-secret")
keycloak_uma = KeycloakUMA(connection=keycloak_connection)The Authorization Code flow involves two steps: requesting the authorization URL and then exchanging the resulting code for an access token.
Use auth_url() to generate the URL where you redirect the user to log in.
Once the user is redirected back to your redirect_uri with a code, use token() with grant_type='authorization_code' to retrieve the tokens.
# 1. Get authorization URL
auth_url = keycloak_openid.auth_url(
redirect_uri="your_call_back_url",
scope="email",
state="your_state_info")
# 2. Get access token with code
access_token = keycloak_openid.token(
grant_type='authorization_code',
code='the_code_you_get_from_auth_url_callback',
redirect_uri="your_call_back_url")To manage Keycloak users, realms, and clients asynchronously, use the KeycloakAdmin class. You can configure it by passing parameters directly to the constructor or by providing a KeycloakOpenIDConnection object for more advanced connection settings (like client credentials or SSL verification).
from keycloak import KeycloakAdmin
from keycloak import KeycloakOpenIDConnection
# Option 1: Direct configuration
admin = KeycloakAdmin(
server_url="http://localhost:8080/",
username='example-admin',
password='secret',
realm_name="master",
user_realm_name="only_if_other_realm_than_master"
)
# Option 2: Using a connection object
keycloak_connection = KeycloakOpenIDConnection(
server_url="http://localhost:8080/",
username='example-admin',
password='secret',
realm_name="master",
user_realm_name="only_if_other_realm_than_master",
client_id="my_client",
client_secret_key="client-secret",
verify=True
)
keycloak_admin = KeycloakAdmin(connection=keycloak_connection)This project requires commits to follow the Conventional Commits specification to automate versioning and changelogs. After setting up your virtual environment, install the pre-commit hooks to enforce this at the commit and push stages.
# Ensure you are in your virtualenv first
pre-commit install --install-hooks -t pre-commit -t pre-push -t commit-msgTo perform administrative tasks, you must instantiate a KeycloakAdmin client. You can configure it in two ways:
KeycloakAdmin constructor.KeycloakOpenIDConnection instance to the KeycloakAdmin constructor. This is recommended for reusing connection settings.Common parameters include:
server_url: The base URL of your Keycloak server.username / password: Credentials for the admin user.realm_name: The realm you are operating in (e.g., master).user_realm_name: The realm where the admin user resides (only if different from realm_name).client_id / client_secret_key: Credentials if using a client-based authentication.pool_maxsize: Maximum size of the connection pool.# Option 1: Direct Configuration
admin = KeycloakAdmin(
server_url="http://localhost:8080/",
username='example-admin',
password='secret',
realm_name="master",
user_realm_name="only_if_other_realm_than_master",
pool_maxsize=20
)
# Option 2: Using a KeycloakOpenIDConnection object
from keycloak import KeycloakAdmin
from keycloak import KeycloakOpenIDConnection
keycloak_connection = KeycloakOpenIDConnection(
server_url="http://localhost:8080/",
username='example-admin',
password='secret',
realm_name="master",
user_realm_name="only_if_other_realm_than_master",
client_id="my_client",
client_secret_key="client-secret",
pool_maxsize=25,
verify=True
)
keycloak_admin = KeycloakAdmin(connection=keycloak_connection)The KeycloakOpenID class is used to interact with Keycloak using OpenID Connect protocols, such as obtaining authorization URLs, exchanging codes for tokens, and managing user sessions.
Common tasks include:
server_url, client_id, realm_name, and client_secret_key..well_known() to retrieve the OpenID configuration..auth_url() to generate the URL for the OAuth authorization request..token() with grant_type='authorization_code' to exchange a code for an access token..token(username, password) for resource owner password credentials..refresh_token(), .userinfo(), and .logout() to manage the user lifecycle.from keycloak import KeycloakOpenID
# Configure client
keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
client_id="example_client",
realm_name="example_realm",
client_secret_key="secret")
# Get WellKnown
config_well_known = keycloak_openid.well_known()
# Get Code With Oauth Authorization Request
auth_url = keycloak_openid.auth_url(
redirect_uri="your_call_back_url",
scope="email",
state="your_state_info")
# Get Access Token With Code
access_token = keycloak_openid.token(
grant_type='authorization_code',
code='the_code_you_get_from_auth_url_callback',
redirect_uri="your_call_back_url")
# Get Token (Password Grant)
token = keycloak_openid.token("user", "password")
# Get Userinfo
userinfo = keycloak_openid.userinfo(token['access_token'])
# Refresh token
token = keycloak_openid.refresh_token(token['refresh_token'])
# Logout
keycloak_openid.logout(token['refresh_token'])