### Setup Development Environment with Poetry Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/contributing.md Commands to initialize a Python virtual environment and install project dependencies using Poetry. ```console # Install and upgrade pip & poetry python -m pip install --upgrade pip poetry # Create virtualenv python -m poetry env use # install package dependencies including dev dependencies python -m poetry install # Activate virtualenv python -m poetry shell ``` -------------------------------- ### Get Client Installation Provider (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously retrieves the content for a specified client installation provider. Requires the client ID and the provider ID. The provider ID determines the response format, with available options listed in ServerInfoRepresentation#clientInstallations. ```python async def a_get_client_installation_provider(client_id: str, provider_id: str) -> dict: """Get content for given installation provider asynchronously.""" pass ``` -------------------------------- ### Get Client Installation Provider (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Asynchronously retrieves installation provider content for a given client ID and provider ID. This function is useful for obtaining client-specific configuration details in various formats. ```python async def a_get_client_installation_provider(client_id: str, provider_id: str) -> dict: """Get content for given installation provider asynchronously.""" # Implementation details would go here ``` -------------------------------- ### Get Keycloak Client Installation Provider (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieves installation provider content for a specific client. Requires the client ID and a provider ID to specify the desired response format. Returns the installation providers configuration. ```python def get_client_installation_provider(client_id: str, provider_id: str) -> dict: """Get content for given installation provider. Args: client_id (str): Client id provider_id (str): provider id to specify response format Returns: dict: Installation providers """ pass ``` -------------------------------- ### Client Installation Provider API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieve installation provider content for a specific client. This endpoint allows fetching configuration details for client installations based on a provider ID. ```APIDOC ## GET /admin/realms/{realm}/clients/{client_id}/installation/{provider_id} ### Description Get content for a given installation provider asynchronously. ### Method GET ### Endpoint `/admin/realms/{realm}/clients/{client_id}/installation/{provider_id}` ### Parameters #### Path Parameters - **client_id** (str) - Required - Client ID. - **provider_id** (str) - Required - Provider ID to specify response format. Possible values can be found in `ServerInfoRepresentation#clientInstallations`. ### Response #### Success Response (200) - **dict** - Installation providers content. ``` -------------------------------- ### Keycloak Admin Client Installation and Protocol Mapper URL Patterns Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md These URL patterns are for managing client installation providers and protocol mappers. They require the realm name, client ID, and optionally a provider ID or protocol mapper ID. ```python URL_ADMIN_CLIENT_INSTALLATION_PROVIDER = 'admin/realms/{realm-name}/clients/{id}/installation/providers/{provider-id}' URL_ADMIN_CLIENT_PROTOCOL_MAPPERS = 'admin/realms/{realm-name}/clients/{id}/protocol-mappers/models' URL_ADMIN_CLIENT_PROTOCOL_MAPPER = 'admin/realms/{realm-name}/clients/{id}/protocol-mappers/models/{protocol-mapper-id}' ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/contributing.md Commands to install pre-commit hooks to enforce conventional commit standards and code quality checks. ```console # Create virtualenv python -m poetry env use # Activate virtualenv python -m poetry shell pre-commit install --install-hooks -t pre-commit -t pre-push -t commit-msg ``` -------------------------------- ### GET /server-info Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves server-wide configuration information. ```APIDOC ## GET /server-info ### Description Retrieves themes, social providers, and other server configuration details. ### Method GET ### Endpoint /server-info ### Response #### Success Response (200) - **serverInfo** (dict) - ServerInfoRepresentation object. ``` -------------------------------- ### Manage UMA Resources with KeycloakUMA Source: https://context7.com/marcospereirampj/python-keycloak/llms.txt Provides examples for managing User-Managed Access (UMA) resources and policies using the KeycloakUMA client. This includes creating, listing, reading, updating, and deleting resource sets, as well as creating and querying permission policies. Requires a KeycloakOpenIDConnection setup. ```python from keycloak import KeycloakOpenIDConnection, KeycloakUMA connection = KeycloakOpenIDConnection( server_url="http://localhost:8080/", username="admin", password="admin", realm_name="my-realm", client_id="my-resource-server", client_secret_key="secret" ) uma = KeycloakUMA(connection=connection) resource = uma.resource_set_create({ "name": "My Document", "type": "document", "ownerManagedAccess": True, "uris": ["/documents/123"], "scopes": ["read", "write", "delete"] }) print(f"Created resource: {resource['_id']}") resource_ids = uma.resource_set_list_ids( name="My Document", exact_name=True ) print(f"Found resources: {resource_ids}") for resource in uma.resource_set_list(): print(f"Resource: {resource['name']}, Scopes: {resource.get('scopes', [])}") resource = uma.resource_set_read(resource_ids[0]) print(f"Resource details: {resource}") uma.resource_set_update( resource_id=resource['_id'], payload={ "name": "Updated Document Name", "scopes": ["read", "write"] } ) uma.policy_resource_create( resource_id=resource['_id'], payload={ "name": "Document Read Policy", "description": "Allow read access to developers group", "scopes": ["read"], "groups": ["/developers"] } ) policies = uma.policy_query(resource=resource['_id']) print(f"Policies: {policies}") uma.resource_set_delete(resource['_id']) ``` -------------------------------- ### GET /serverinfo Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieves server configuration information including themes and social providers. ```APIDOC ## GET /serverinfo ### Description Fetches server-level information such as themes and social providers. ### Method GET ### Endpoint /serverinfo ### Response #### Success Response (200) - **info** (dict) - ServerInfoRepresentation object. ``` -------------------------------- ### Get All Clients (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously retrieves a list of all clients belonging to the realm. Returns a list of ClientRepresentation dictionaries. ```python async def a_get_clients() -> list: """Get clients asynchronously.""" # Implementation details... ``` -------------------------------- ### Get Server Info API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieve server information including themes and social providers asynchronously. ```APIDOC ## GET /serverinfo ### Description Get themes, social providers, etc. on this server asynchronously. ### Method GET ### Endpoint /serverinfo ### Response #### Success Response (200) - **ServerInfoRepresentation** (dict) - ServerInfoRepresentation #### Response Example ```json { "themes": { "admin": ["keycloak", "base"], "account": ["keycloak", "base"] }, "social": [ {"id": "google", "name": "Google", "enabled": true}, {"id": "facebook", "name": "Facebook", "enabled": false} ] } ``` ``` -------------------------------- ### KeycloakAdmin Client Initialization Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Documentation for initializing the KeycloakAdmin client, including all available parameters. ```APIDOC ## KeycloakAdmin Client ### Description Keycloak Admin client for interacting with Keycloak server. ### Class `keycloak.KeycloakAdmin` ### Parameters * **server_url** (*str*) – Keycloak server url * **grant_type** (*str*) – Type of grant to use for authentication. * **username** (*str*) – admin username * **password** (*str*) – admin password * **token** (*dict*) – access and refresh tokens * **totp** (*int*) – Time based OTP * **realm_name** (*str*) – realm name (defaults to 'master') * **client_id** (*str*) – client id (defaults to 'admin-cli') * **verify** (*Union* *[**bool* *,**str* *]*) – Boolean value to enable or disable certificate validation or a string containing a path to a CA bundle to use * **client_secret_key** (*str*) – client secret key (optional, required only for access type confidential) * **custom_headers** (*dict*) – dict of custom header to pass to each HTML request * **user_realm_name** (*str*) – The realm name of the user, if different from realm_name * **timeout** (*int*) – connection timeout in seconds (defaults to 60) * **cert** (*Union* *[**str* *,**Tuple* *[**str* *,**str* *]* *]*) – An SSL certificate used by the requested host to authenticate the client. Either a path to an SSL certificate file, or two-tuple of (certificate file, key file). * **max_retries** (*int*) – The total number of times to retry HTTP requests (defaults to 1). * **connection** ([*KeycloakOpenIDConnection*](#keycloak.openid_connection.KeycloakOpenIDConnection)) – A KeycloakOpenIDConnection as an alternative to individual params. * **pool_maxsize** (*int*) – The maximum number of connections to save in the pool. ``` -------------------------------- ### Generate Initial Access Tokens in Python Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Creates an initial access token used for registering new clients. The method accepts the number of allowed registrations and the expiration time in days. ```python token = keycloak_admin.create_initial_access_token(count=1, expiration=1) ``` -------------------------------- ### Configure Keycloak and Register Clients Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Utility functions for loading authorization configurations from JSON files and registering new clients within the Keycloak realm. ```python async def a_load_authorization_config(path: str) -> None: pass async def a_register_client(token: str, payload: dict) -> dict: pass ``` -------------------------------- ### POST /clients Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Registers a new client in Keycloak using an initial access token. ```APIDOC ## POST /clients ### Description Create a new client in Keycloak. ### Method POST ### Endpoint /clients ### Parameters #### Request Body - **token** (str) - Required - Initial access token - **payload** (dict) - Required - ClientRepresentation object ### Response #### Success Response (200) - **client** (dict) - Client Representation ``` -------------------------------- ### Asynchronous Paginated GET Requests in Python Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously fetches data by paginating over GET requests. It handles multiple pages of results and combines them into a single list. Requires a URL and optional query parameters. ```python async def a___fetch_all(url: str, query: dict | None = None) -> list: """Paginate asynchronously over get requests . Wrapper function to paginate GET requests. * **Parameters:** * **url** (*str*) – The url on which the query is executed * **query** (*dict*) – Existing query parameters (optional) * **Returns:** Combined results of paginated queries * **Return type:** list """ pass ``` -------------------------------- ### Get Client Roles of Client Scope (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously retrieves all client roles for a client's scope. Use `a_get_client_roles_of_client_scope` for getting client-specific roles. Requires client IDs. Returns a list of RoleRepresentations from the Keycloak server. ```python async def a_get_client_roles_of_client_scope(client_id: str, client_roles_owner_id: str) -> list: """ Get all client roles for a client’s scope asynchronously. To get roles from a client scope, use a_get_client_roles_of_client_scope. * **Parameters:** * **client_id** (*str*) – id of client (not client-id) * **client_roles_owner_id** (*str*) – id of client (not client-id) who has the roles * **Returns:** Keycloak server response (array RoleRepresentation) * **Return type:** dict """ pass ``` -------------------------------- ### KeycloakOpenID Client Initialization (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Initializes the Keycloak OpenID client for interacting with Keycloak servers. It requires server URL, realm name, and client ID, with optional parameters for client secret, certificate validation, custom headers, proxies, and timeouts. ```python class KeycloakOpenID: def __init__(self, server_url: str, realm_name: str, client_id: str, client_secret_key: str | None = None, verify: bool | str = True, custom_headers: dict | None = None, proxies: dict | None = None, timeout: int | None = 60, cert: str | tuple | None = None, max_retries: int = 1, pool_maxsize: int | None = None): """ Keycloak OpenID client. * **Parameters:** * **server_url** – Keycloak server url * **client_id** – client id * **realm_name** – realm name * **client_secret_key** – client secret key * **verify** – Boolean value to enable or disable certificate validation or a string containing a path to a CA bundle to use * **custom_headers** – dict of custom header to pass to each HTML request * **proxies** – dict of proxies to sent the request by. * **timeout** – connection timeout in seconds * **cert** – An SSL certificate used by the requested host to authenticate the client. Either a path to an SSL certificate file, or two-tuple of (certificate file, key file). * **max_retries** – The total number of times to retry HTTP requests. * **pool_maxsize** (*int*) – The maximum number of connections to save in the pool. """ pass ``` -------------------------------- ### GET /authentication/providers Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieve a list of available authenticator providers. ```APIDOC ## GET /authentication/providers ### Description Returns a list of all available authenticator providers configured in the Keycloak instance. ### Method GET ### Endpoint /authentication/providers ### Response #### Success Response (200) - **providers** (list) - List of authenticator providers. ### Response Example [ "auth-cookie", "auth-otp" ] ``` -------------------------------- ### Manage OAuth2/OIDC Clients Source: https://context7.com/marcospereirampj/python-keycloak/llms.txt Provides examples for creating and configuring confidential clients, retrieving client secrets, and managing service account users. Useful for setting up backend service authentication. ```python client_id = keycloak_admin.create_client({ "clientId": "my-backend-service", "publicClient": False, "serviceAccountsEnabled": True }, skip_exists=True) secrets = keycloak_admin.get_client_secrets(client_id) service_account = keycloak_admin.get_client_service_account_user(client_id) keycloak_admin.delete_client(client_id) ``` -------------------------------- ### Get Group Members Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves all members of a specified group. ```APIDOC ## GET /admin/realms/{realm}/groups/{groupId}/members ### Description Retrieves all members belonging to a specified group. ### Method GET ### Endpoint `/admin/realms/{realm}/groups/{groupId}/members` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. - **groupId** (string) - Required - The ID of the group whose members are to be retrieved. #### Query Parameters - **query** (dict) - Optional - Additional query parameters for filtering or pagination of members. Refer to Keycloak API documentation for available options. ### Response #### Success Response (200) - **list** (array) - Returns a list of UserRepresentation objects representing the group members. #### Response Example ```json [ { "id": "user_id_789", "username": "testuser", "firstName": "Test", "lastName": "User", "email": "test@example.com" } ] ``` ``` -------------------------------- ### Get Client Authorization Settings (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously retrieves the authorization configuration settings for a specific client. Requires the client_id as a string parameter. Returns the authorization settings as a dictionary. ```python async def a_get_client_authz_settings(client_id: str) -> dict: """Get authorization json from client asynchronously.""" # Implementation details... ``` -------------------------------- ### Import Client Authorization Configuration (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously imports client authorization configuration into Keycloak. Requires the client_id and a payload dictionary representing the ResourceServerRepresentation. Returns the server's response. ```python async def a_import_client_authz_config(client_id: str, payload: dict) -> dict: """Import client authorization configuration asynchronously.""" # Implementation details... ``` -------------------------------- ### GET /groups Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves a list of groups belonging to the realm. ```APIDOC ## GET /groups ### Description Returns a list of groups belonging to the realm. Supports optional hierarchy expansion. ### Method GET ### Endpoint /groups ### Parameters #### Query Parameters - **full_hierarchy** (bool) - Optional - If True, returns nested children groups. ### Response #### Success Response (200) - **groups** (list) - Array of GroupRepresentation objects. ``` -------------------------------- ### GET /authentication/authenticator-providers Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves a list of available authenticator providers. ```APIDOC ## GET /authentication/authenticator-providers ### Description Get authenticator providers list. ### Method GET ### Endpoint /authentication/authenticator-providers ### Response #### Success Response (200) - **providers** (list) - List of authenticator providers ``` -------------------------------- ### Assemble UMA Permissions with Resource and Scope Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/uma_permissions/index.md Demonstrates how to create Resource and Scope objects and combine them to form a permission string using the UMAPermission class interface. ```python from keycloak.uma_permissions import Resource, Scope # Create a resource and a scope r = Resource("Users") s = Scope("delete") # Combine them to form a permission permission = r(s) print(permission) # Output: 'Users#delete' ``` -------------------------------- ### Get All Users API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves a list of all users in the realm. ```APIDOC ## GET /admin/realms/{realm-name}/users ### Description Retrieves a list of all users in the realm. ### Method GET ### Endpoint /admin/realms/{realm-name}/users ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the realm. #### Query Parameters - **briefRepresentation** (boolean) - Optional - If true, returns only basic user information. - **count** (integer) - Optional - The number of users to return. - **email** (string) - Optional - Filter by email address. - **exact** (boolean) - Optional - If true, performs an exact match for the search query. - **first** (integer) - Optional - The first result to return (pagination). - **firstName** (string) - Optional - Filter by first name. - **lastName** (string) - Optional - Filter by last name. - **q** (string) - Optional - A query string for searching users. - **search** (boolean) - Optional - If true, enables searching by username, first name, and last name. ### Response #### Success Response (200) - **users** (array) - A list of user objects. #### Response Example { "users": [ { "id": "user-id-1", "username": "user1", "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com" }, { "id": "user-id-2", "username": "user2", "firstName": "Jane", "lastName": "Smith", "email": "jane.smith@example.com" } ] } ``` -------------------------------- ### Async Server Information Retrieval in Python Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously fetch general server information, including themes and social providers. This function does not require any parameters and returns a dictionary containing server details. ```python async def a_get_server_info() -> dict: """Get themes, social providers, etc. on this server asynchronously.""" pass ``` -------------------------------- ### Python KeycloakAdmin Client Configuration Source: https://context7.com/marcospereirampj/python-keycloak/llms.txt Demonstrates three methods to initialize the KeycloakAdmin client for administrative operations. It shows configuration using KeycloakOpenIDConnection, direct initialization with credentials, and initialization using client credentials for service accounts. Requires the keycloak library. ```python from keycloak import KeycloakAdmin, KeycloakOpenIDConnection # Method 1: Using KeycloakOpenIDConnection (recommended) keycloak_connection = KeycloakOpenIDConnection( server_url="http://localhost:8080/", username="admin", password="admin-password", realm_name="master", client_id="admin-cli", verify=True ) keycloak_admin = KeycloakAdmin(connection=keycloak_connection) # Method 2: Direct initialization keycloak_admin = KeycloakAdmin( server_url="http://localhost:8080/", username="admin", password="admin-password", realm_name="master", client_id="admin-cli", verify=True ) # Method 3: Using client credentials (service account) keycloak_admin = KeycloakAdmin( server_url="http://localhost:8080/", client_id="admin-service", client_secret_key="service-secret", realm_name="master", grant_type="client_credentials" ) # Get current realm print(f"Current realm: {keycloak_admin.get_current_realm()}") # Change realm context keycloak_admin.change_current_realm("my-realm") ``` -------------------------------- ### GET /public_key Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieve the public key exposed by the Keycloak realm. ```APIDOC ## GET /public_key ### Description Retrieve the public key exposed by the realm page. ### Method GET ### Endpoint /public_key ### Response #### Success Response (200) - **key** (str) - The public key string #### Response Example { "key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----" } ``` -------------------------------- ### Get Group by Path Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves group details using its path. ```APIDOC ## GET /admin/realms/{realm}/groups?path={path} ### Description Retrieves group details based on its name or path. ### Method GET ### Endpoint `/admin/realms/{realm}/groups` ### Parameters #### Path Parameters - **realm** (string) - Required - The realm name. #### Query Parameters - **path** (string) - Required - The path of the group to retrieve. ### Response #### Success Response (200) - **GroupRepresentation** (dict) - Returns full group details for the group defined by the path. #### Response Example ```json { "id": "group_id_123", "name": "Example Group", "subGroups": [], "access": {}, "clientRoles": {}, "attributes": {} } ``` ``` -------------------------------- ### Create Client Authorization Policy Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Demonstrates how to create a new authorization policy for a specific client using a dictionary payload. The payload defines the policy type, logic, and decision strategy. ```python payload = { "type": "client", "logic": "POSITIVE", "decisionStrategy": "UNANIMOUS", "name": "My Policy", "clients": ["other_client_id"] } await keycloak_admin.a_create_client_authz_client_policy(payload, client_id="my-client-id") ``` -------------------------------- ### GET /client-authz-policies Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Endpoints for managing client authorization policies and permissions. ```APIDOC ## GET /clients/{client_id}/authz/policies ### Description Retrieves a list of authorization policies associated with a specific client. ### Method GET ### Parameters #### Path Parameters - **client_id** (str) - Required - The unique identifier of the client. ### Response #### Success Response (200) - **policies** (list) - List of RoleRepresentation objects. --- ## POST /clients/{client_id}/authz/policies ### Description Creates a new authorization policy for the specified client. ### Method POST ### Parameters #### Path Parameters - **client_id** (str) - Required - The unique identifier of the client. #### Request Body - **payload** (dict) - Required - Policy configuration (e.g., type, logic, decisionStrategy, name). ### Request Example { "type": "client", "logic": "POSITIVE", "decisionStrategy": "UNANIMOUS", "name": "My Policy", "clients": ["other_client_id"] } ``` -------------------------------- ### Create Client Authorization Policy (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Creates a new authorization policy for a given client. Requires a payload dictionary containing policy details and the client ID. Returns the created policy details. ```python def create_client_authz_client_policy(payload: dict, client_id: str) -> dict: """Create a new policy for a given client.""" # Example payload: # payload={ # "type": "client", # "logic": "POSITIVE", # "decisionStrategy": "UNANIMOUS", # "name": "My Policy", # "clients": [other_client_id], # } # Implementation details would go here pass ``` -------------------------------- ### Create Client Authorization Resource (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Asynchronously creates authorization resources for a client. Requires the client_id and a payload dictionary representing the ResourceRepresentation. An optional boolean skip_exists parameter can prevent creation if the resource already exists. Returns the Keycloak server's response. ```python async def a_create_client_authz_resource(client_id: str, payload: dict, skip_exists: bool = False) -> dict: """Create resources of client asynchronously.""" # Implementation details... ``` -------------------------------- ### GET /client-scopes Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves a list of client scopes for the current realm. ```APIDOC ## GET /client-scopes ### Description Get representation of the client scopes for the realm. ### Method GET ### Endpoint /client-scopes ### Response #### Success Response (200) - **scopes** (list) - Array of ClientScopeRepresentation ``` -------------------------------- ### GET /authentication/config/{config_id} Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieves detailed configuration for a specific authenticator. ```APIDOC ## GET /authentication/config/{config_id} ### Description Get authenticator configuration details. ### Method GET ### Endpoint /authentication/config/{config_id} ### Parameters #### Path Parameters - **config_id** (str) - Required - Authenticator config id ### Response #### Success Response (200) - **config** (dict) - Authenticator configuration details ``` -------------------------------- ### Initialize Permission Class Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/authorization/permission/index.md Demonstrates how to instantiate the Permission class, which requires a name, type, logic, and decision strategy. This object serves as the foundation for defining authorization policies. ```python from keycloak.authorization.permission import Permission # Initialize a new permission instance perm = Permission( name="View Account", type="resource", logic="POSITIVE", decision_strategy="UNANIMOUS" ) print(perm.name) print(perm.decision_strategy) ``` -------------------------------- ### Get User Groups API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves all groups a user is a member of. ```APIDOC ## GET /admin/realms/{realm-name}/users/{id}/groups ### Description Retrieves all groups a user is a member of. ### Method GET ### Endpoint /admin/realms/{realm-name}/users/{id}/groups ### Parameters #### Path Parameters - **realm-name** (string) - Required - ``` -------------------------------- ### Prepare HTTpx Request Content in Python Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md A static utility method to prepare the correct content keyword argument for httpx.AsyncClient.request(). It ensures compatibility with httpx's request handling, especially for different data types like dictionaries, strings, or multipart encoders. ```python from requests_toolbelt import MultipartEncoder @staticmethod def _prepare_httpx_request_content(data: dict | str | None | MultipartEncoder) -> dict: """Create the correct request content kwarg to httpx.AsyncClient.request().""" # See https://www.python-httpx.org/compatibility/#request-content # Implementation details omitted for brevity pass ``` -------------------------------- ### GET /roles/{role_id} Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieve a specific role representation by its unique ID. ```APIDOC ## GET /roles/{role_id} ### Description Fetch the details of a specific role using its unique identifier. ### Method GET ### Endpoint /roles/{role_id} ### Parameters #### Path Parameters - **role_id** (str) - Required - The unique ID of the role. ### Response #### Success Response (200) - **role** (dict) - RoleRepresentation object. #### Response Example { "id": "role-uuid", "name": "admin", "composite": false } ``` -------------------------------- ### Create Keycloak Client (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Creates a new client in Keycloak. Optionally skips creation if the client already exists. Requires a payload dictionary representing the ClientRepresentation and a boolean to control skipping existing clients. Returns the client ID upon successful creation. ```python def create_client(payload: dict, skip_exists: bool = False) -> str: """Create a client. Args: payload (dict): ClientRepresentation skip_exists (bool): If true then do not raise an error if client already exists. Returns: str: Client ID """ pass ``` -------------------------------- ### GET /client-roles Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Endpoints for retrieving composite roles and child role relationships. ```APIDOC ## GET /clients/{client_id}/groups/{group_id}/roles ### Description Retrieves composite client roles assigned to a specific group. ### Parameters #### Path Parameters - **client_id** (str) - Required - **group_id** (str) - Required #### Query Parameters - **brief_representation** (bool) - Optional - Whether to omit attributes in the response. --- ## GET /clients/{client_id}/roles/{role_id}/children ### Description Retrieves child roles of a composite client role. ### Parameters #### Path Parameters - **client_id** (str) - Required - **role_id** (str) - Required ``` -------------------------------- ### GET /clients/{client_id}/authz/policies Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieves authorization policies for a specific client. ```APIDOC ## GET /clients/{client_id}/authz/policies ### Description Retrieves a list of authorization policies associated with the specified client. ### Method GET ### Endpoint /clients/{client_id}/authz/policies ### Parameters #### Path Parameters - **client_id** (str) - Required - The unique ID of the client. ### Response #### Success Response (200) - **policies** (list) - A list of RoleRepresentation objects. #### Response Example [ {"id": "policy-123", "name": "My Policy"} ] ``` -------------------------------- ### Get User Sessions API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieve sessions associated with a user asynchronously. ```APIDOC ## GET /users/{user_id}/sessions ### Description Get sessions associated with the user asynchronously. ### Method GET ### Endpoint /users/{user_id}/sessions ### Parameters #### Path Parameters - **user_id** (str) - Required - Id of user ### Response #### Success Response (200) - **UserSessionRepresentation** (list) - UserSessionRepresentation #### Response Example ```json [ { "id": "session-id-123", "ipAddress": "192.168.1.100", "started": 1678886400, "lastAccess": 1678887000, "client": "my-client" } ] ``` ``` -------------------------------- ### ConnectionManager Initialization Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Initializes a new connection to the Keycloak server using the ConnectionManager class. ```APIDOC ## POST /connection/initialize ### Description Initializes a connection manager instance to handle requests to the Keycloak server. ### Method POST ### Endpoint /connection/initialize ### Parameters #### Request Body - **base_url** (str) - Required - The server URL. - **headers** (dict) - Optional - Custom headers for requests. - **timeout** (int) - Optional - Request timeout in seconds (default 60). - **verify** (bool/str) - Optional - Enable/disable SSL verification or path to CA bundle. - **max_retries** (int) - Optional - Number of retries for failed requests. ### Request Example { "base_url": "https://keycloak.example.com", "timeout": 30 } ### Response #### Success Response (200) - **status** (string) - Connection initialized successfully. #### Response Example { "status": "success" } ``` -------------------------------- ### Initial Access Tokens Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Endpoint for creating initial access tokens for client registration. ```APIDOC ## POST /initial-access-token ### Description Creates an initial access token to allow client registration. ### Method POST ### Endpoint /initial-access-token ### Parameters #### Query Parameters - **count** (int) - Optional - Number of clients that can be registered. - **expiration** (int) - Optional - Days until expiration. ### Response #### Success Response (200) - **token** (dict) - The generated initial access token. ``` -------------------------------- ### GET /clients/{client_id}/authz/settings Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieve the authorization settings for a specific client. ```APIDOC ## GET /clients/{client_id}/authz/settings ### Description Retrieves the authorization JSON configuration for a given client. ### Method GET ### Endpoint /clients/{client_id}/authz/settings ### Parameters #### Path Parameters - **client_id** (str) - Required - The unique ID of the client. ### Response #### Success Response (200) - **settings** (dict) - The authorization configuration object. #### Response Example { "allowRemoteResourceManagement": true, "policyEnforcementMode": "ENFORCING" } ``` -------------------------------- ### List All Realms - Python Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/keycloak_admin/index.md Retrieves a list of all realms configured in the Keycloak deployment. Returns a list of realm names. ```python def get_realms() -> list: """List all realms in Keycloak deployment.""" pass ``` -------------------------------- ### GET /admin/realms/{realm-name}/organizations Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Manages organization-related operations within a realm. ```APIDOC ## GET /admin/realms/{realm-name}/organizations ### Description Lists all organizations associated with the specified realm. ### Method GET ### Endpoint /admin/realms/{realm-name}/organizations ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the Keycloak realm. ### Response #### Success Response (200) - **organizations** (array) - List of organization objects. ``` -------------------------------- ### GET /admin/realms/{realm-name}/admin-events Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves the admin events for a specific realm. ```APIDOC ## GET /admin/realms/{realm-name}/admin-events ### Description Retrieves the administrative events logged within the specified realm. ### Method GET ### Endpoint /admin/realms/{realm-name}/admin-events ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the Keycloak realm. ### Response #### Success Response (200) - **events** (array) - List of admin event objects. ``` -------------------------------- ### Create User and Set Initial Password Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/modules/admin.md Creates a new user and simultaneously sets their initial password. The password is provided as part of the user's credentials. ```python 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",}]} ``` -------------------------------- ### Get User Sessions API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves all active sessions for a specific user. ```APIDOC ## GET /admin/realms/{realm-name}/users/{id}/sessions ### Description Retrieves all active sessions for a specific user. ### Method GET ### Endpoint /admin/realms/{realm-name}/users/{id}/sessions ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the realm. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **sessions** (array) - A list of session objects. #### Response Example [ { "id": "session-id-1", "ipAddress": "192.168.1.100", "started": 1678882800, "lastAccess": 1678886400 } ] ``` -------------------------------- ### Upload Client Certificate (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Uploads a new certificate for a client. Requires the client ID and the certificate content as a string. Returns a dictionary confirming the upload. ```python def upload_certificate(client_id: str, certcont: str) -> dict: """Upload a new certificate for the client.""" # Returns dictionary {"certificate": ""} # Implementation details would go here pass ``` -------------------------------- ### Get User Consents API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves all consents granted by a specific user. ```APIDOC ## GET /admin/realms/{realm-name}/users/{id}/consents ### Description Retrieves all consents granted by a specific user. ### Method GET ### Endpoint /admin/realms/{realm-name}/users/{id}/consents ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the realm. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **consents** (array) - A list of consent objects. #### Response Example [ { "clientId": "client-id-1", "grantedScopes": ["openid", "profile"] } ] ``` -------------------------------- ### Create User (Raise Exception if Exists) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/modules/admin.md Creates a new user, raising an exception if the username already exists. ```APIDOC ## Add User and Raise Exception if Username Already Exists ### Description Creates a new user, but will raise an exception if a user with the same username already exists. This is controlled by the `exist_ok=False` parameter. ### Method POST ### Endpoint `/admin/realms/{realm}/users` (Internal representation, actual endpoint handled by library) ### Parameters #### Path Parameters None #### Query Parameters * **exist_ok** (boolean) - Required - Set to `False` to raise an exception if the username already exists. #### Request Body * **email** (string) - Required - The user's email address. * **username** (string) - Required - The user's username. * **enabled** (boolean) - Required - Whether the user account is enabled. * **firstName** (string) - Optional - The user's first name. * **lastName** (string) - Optional - The user's last name. ### Request Example ```python new_user = keycloak_admin.create_user({"email": "example@example.com", "username": "example@example.com", "enabled": True, "firstName": "Example", "lastName": "Example"}, exist_ok=False) ``` ### Response #### Success Response (200) Returns the created user object, including the user ID. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "createdTimestamp": 1678886400000, "username": "example@example.com", "enabled": true, "firstName": "Example", "lastName": "Example", "email": "example@example.com" } ``` ``` -------------------------------- ### Create User Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/modules/admin.md Creates a new user in Keycloak. Supports basic user details and optional flags. ```APIDOC ## Create User ### Description Creates a new user in Keycloak with the provided user attributes. The `exist_ok` parameter defaults to `True` for backward compatibility. ### Method POST ### Endpoint `/admin/realms/{realm}/users` (Internal representation, actual endpoint handled by library) ### Parameters #### Path Parameters None #### Query Parameters * **exist_ok** (boolean) - Optional - If `False`, raises an exception if the username already exists. #### Request Body * **email** (string) - Required - The user's email address. * **username** (string) - Required - The user's username. * **enabled** (boolean) - Required - Whether the user account is enabled. * **firstName** (string) - Optional - The user's first name. * **lastName** (string) - Optional - The user's last name. * **credentials** (array) - Optional - A list of credential objects, e.g., `[{"value": "secret","type": "password"}]`. * **attributes** (object) - Optional - A key-value map for custom user attributes, e.g., `{"locale": ["fr"]}`. ### Request Example ```python new_user = keycloak_admin.create_user({"email": "example@example.com", "username": "example@example.com", "enabled": True, "firstName": "Example", "lastName": "Example"}) ``` ### Response #### Success Response (200) Returns the created user object, including the user ID. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "createdTimestamp": 1678886400000, "username": "example@example.com", "enabled": true, "firstName": "Example", "lastName": "Example", "email": "example@example.com" } ``` ``` -------------------------------- ### Get User by ID API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves details for a specific user by their ID. ```APIDOC ## GET /admin/realms/{realm-name}/users/{id} ### Description Retrieves details for a specific user by their ID. ### Method GET ### Endpoint /admin/realms/{realm-name}/users/{id} ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the realm. - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **id** (string) - The user's ID. - **username** (string) - The user's username. - **firstName** (string) - The user's first name. - **lastName** (string) - The user's last name. - **email** (string) - The user's email address. #### Response Example { "id": "user-id-1", "username": "user1", "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Get User Count API Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/urls_patterns/index.md Retrieves the total count of users in the realm. ```APIDOC ## GET /admin/realms/{realm-name}/users/count ### Description Retrieves the total count of users in the realm. ### Method GET ### Endpoint /admin/realms/{realm-name}/users/count ### Parameters #### Path Parameters - **realm-name** (string) - Required - The name of the realm. ### Response #### Success Response (200) - **count** (integer) - The total number of users. #### Response Example { "count": 150 } ``` -------------------------------- ### Initialize KeycloakOpenID Client Source: https://context7.com/marcospereirampj/python-keycloak/llms.txt Configures the KeycloakOpenID client to interact with OpenID Connect endpoints. It requires server details and authentication credentials, and provides access to well-known configuration metadata. ```python from keycloak import KeycloakOpenID # Initialize the OpenID client keycloak_openid = KeycloakOpenID( server_url="http://localhost:8080/", client_id="my-app", realm_name="my-realm", client_secret_key="client-secret-key", # Required for confidential clients verify=True, # SSL certificate verification timeout=60, # Connection timeout in seconds max_retries=3, # Retry count for failed requests custom_headers={"X-Custom-Header": "value"} # Optional custom headers ) # Get OpenID Connect well-known configuration config = keycloak_openid.well_known() print(f"Token endpoint: {config['token_endpoint']}") print(f"Authorization endpoint: {config['authorization_endpoint']}") ``` -------------------------------- ### Perform Raw GET Request with ConnectionManager (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/connection/index.md Submits a raw GET request to a specified path on the Keycloak server using the ConnectionManager. It allows for additional keyword arguments to be passed to the underlying requests library. This method can raise a KeycloakConnectionError if the connection fails. ```python try: response = conn.raw_get("/realms") print(response.json()) except KeycloakConnectionError as e: print(f"Connection error: {e}") ``` -------------------------------- ### GET /roles/{role_id}/composites Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/index.md Retrieve composite roles associated with a specific role. ```APIDOC ## GET /roles/{role_id}/composites ### Description Retrieves a list of composite roles associated with the specified role ID. ### Method GET ### Endpoint /roles/{role_id}/composites ### Parameters #### Path Parameters - **role_id** (str) - Required - The ID of the role. #### Query Parameters - **first** (int) - Optional - Pagination offset. - **max** (int) - Optional - Maximum results to return. - **search** (str) - Optional - Search string for filtering roles. ### Response #### Success Response (200) - **roles** (list) - List of RoleRepresentation objects. ``` -------------------------------- ### Prepare httpx Request Content (Python) Source: https://github.com/marcospereirampj/python-keycloak/blob/master/docs/source/reference/keycloak/connection/index.md A static utility method to prepare the correct content keyword argument for `httpx.AsyncClient.request()`. This ensures compatibility with `httpx`'s requirements for request bodies, handling dictionaries, strings, and multipart encoders. ```python def _prepare_httpx_request_content(data: dict | str | None | requests_toolbelt.MultipartEncoder) -> dict: """Create the correct request content kwarg to httpx.AsyncClient.request().""" # See https://www.python-httpx.org/compatibility/#request-content # Implementation details... pass ```