keycloak

Python-Keycloak library.

Subpackages

Submodules

Package Contents

Classes

ConnectionManager

Represents a simple server connection.

KeycloakAdmin

Keycloak Admin client.

KeycloakOpenID

Keycloak OpenID client.

Attributes

__version__

keycloak.__version__ = 0.0.0[source]
class keycloak.ConnectionManager(base_url, headers={}, timeout=60, verify=True, proxies=None)[source]

Bases: object

Represents a simple server connection.

Parameters
  • base_url (str) – The server URL.

  • headers (dict) – The header parameters of the requests to the server.

  • timeout (int) – Timeout to use for requests to the server.

  • verify (bool) – Verify server SSL.

  • proxies (dict) – The proxies servers requests is sent by.

property base_url

Return base url in use for requests to the server.

Returns

Base URL

Return type

str

property timeout

Return timeout in use for request to the server.

Returns

Timeout

Return type

int

property verify

Return verify in use for request to the server.

Returns

Verify indicator

Return type

bool

property headers

Return header request to the server.

Returns

Request headers

Return type

dict

__del__()

Del method.

param_headers(key)

Return a specific header parameter.

Parameters

key (str) – Header parameters key.

Returns

If the header parameters exist, return its value.

Return type

str

clean_headers()

Clear header parameters.

exist_param_headers(key)

Check if the parameter exists in the header.

Parameters

key (str) – Header parameters key.

Returns

If the header parameters exist, return True.

Return type

bool

add_param_headers(key, value)

Add a single parameter inside the header.

Parameters
  • key (str) – Header parameters key.

  • value (str) – Value to be added.

del_param_headers(key)

Remove a specific parameter.

Parameters

key (str) – Key of the header parameters.

raw_get(path, **kwargs)

Submit get request to the path.

Parameters
  • path (str) – Path for request.

  • kwargs (dict) – Additional arguments

Returns

Response the request.

Return type

Response

Raises

KeycloakConnectionError – HttpError Can’t connect to server.

raw_post(path, data, **kwargs)

Submit post request to the path.

Parameters
  • path (str) – Path for request.

  • data (dict) – Payload for request.

  • kwargs (dict) – Additional arguments

Returns

Response the request.

Return type

Response

Raises

KeycloakConnectionError – HttpError Can’t connect to server.

raw_put(path, data, **kwargs)

Submit put request to the path.

Parameters
  • path (str) – Path for request.

  • data (dict) – Payload for request.

  • kwargs (dict) – Additional arguments

Returns

Response the request.

Return type

Response

Raises

KeycloakConnectionError – HttpError Can’t connect to server.

raw_delete(path, data=None, **kwargs)

Submit delete request to the path.

Parameters
  • path (str) – Path for request.

  • data (dict | None) – Payload for request.

  • kwargs (dict) – Additional arguments

Returns

Response the request.

Return type

Response

Raises

KeycloakConnectionError – HttpError Can’t connect to server.

exception keycloak.KeycloakAuthenticationError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakError

Keycloak authentication error exception.

exception keycloak.KeycloakAuthorizationConfigError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak authorization config exception.

exception keycloak.KeycloakConnectionError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakError

Keycloak connection error exception.

exception keycloak.KeycloakDeleteError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak request delete error exception.

exception keycloak.KeycloakDeprecationError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakError

Keycloak deprecation error exception.

exception keycloak.KeycloakError(error_message='', response_code=None, response_body=None)[source]

Bases: Exception

Base class for custom Keycloak errors.

Parameters
  • error_message (str) – The error message

  • response_code (int) – The response status code

__str__()

Str method.

Returns

String representation of the object

Return type

str

exception keycloak.KeycloakGetError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak request get error exception.

exception keycloak.KeycloakInvalidTokenError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak invalid token exception.

exception keycloak.KeycloakOperationError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakError

Keycloak operation error exception.

exception keycloak.KeycloakPostError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak request post error exception.

exception keycloak.KeycloakPutError(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak request put error exception.

exception keycloak.KeycloakRPTNotFound(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak RPT not found exception.

exception keycloak.KeycloakSecretNotFound(error_message='', response_code=None, response_body=None)[source]

Bases: KeycloakOperationError

Keycloak secret not found exception.

class keycloak.KeycloakAdmin(server_url, username=None, password=None, totp=None, realm_name='master', client_id='admin-cli', verify=True, client_secret_key=None, custom_headers=None, user_realm_name=None, auto_refresh_token=None, timeout=60)[source]

Keycloak Admin client.

Parameters
  • server_url (str) – Keycloak server url

  • username (str) – admin username

  • password (str) – admin password

  • totp (str) – Time based OTP

  • realm_name (str) – realm name

  • client_id (str) – client id

  • verify (bool) – True if want check connection SSL

  • 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

  • auto_refresh_token (list) – list of methods that allows automatic token refresh. Ex: [‘get’, ‘put’, ‘post’, ‘delete’]

  • timeout (int) – connection timeout in seconds

property server_url

Get server url.

Returns

Keycloak server url

Return type

str

property realm_name

Get realm name.

Returns

Realm name

Return type

str

property connection

Get connection.

Returns

Connection manager

Return type

ConnectionManager

property client_id

Get client id.

Returns

Client id

Return type

str

property client_secret_key

Get client secret key.

Returns

Client secret key

Return type

str

property verify

Get verify.

Returns

Verify indicator

Return type

bool

property username

Get username.

Returns

Admin username

Return type

str

property password

Get password.

Returns

Admin password

Return type

str

property totp

Get totp.

Returns

TOTP

Return type

str

property token

Get token.

Returns

Access and refresh token

Return type

dict

property auto_refresh_token

Get auto refresh token.

Returns

List of methods for automatic token refresh

Return type

list

property user_realm_name

Get user realm name.

Returns

User realm name

Return type

str

property custom_headers

Get custom headers.

Returns

Custom headers

Return type

dict

PAGE_SIZE = 100
_server_url
_username
_password
_totp
_realm_name
_client_id
_verify
_client_secret_key
_auto_refresh_token
_connection
_token
_custom_headers
_user_realm_name
__fetch_all(url, query=None)

Paginate 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

__fetch_paginated(url, query=None)

Make a specific paginated request.

Parameters
  • url (str) – The url on which the query is executed

  • query (dict) – Pagination settings

Returns

Response

Return type

dict

import_realm(payload)

Import a new realm from a RealmRepresentation.

Realm name must be unique.

RealmRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation

Parameters

payload (dict) – RealmRepresentation

Returns

RealmRepresentation

Return type

dict

export_realm(export_clients=False, export_groups_and_role=False)

Export the realm configurations in the json format.

RealmRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_partialexport

Parameters
  • export_clients (bool) – Skip if not want to export realm clients

  • export_groups_and_role (bool) – Skip if not want to export realm groups and roles

Returns

realm configurations JSON

Return type

dict

get_realms()

List all realms in Keycloak deployment.

Returns

realms list

Return type

list

get_realm(realm_name)

Get a specific realm.

RealmRepresentation: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation

Parameters

realm_name (str) – Realm name (not the realm id)

Returns

RealmRepresentation

Return type

dict

create_realm(payload, skip_exists=False)

Create a realm.

RealmRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation

Parameters
  • payload (dict) – RealmRepresentation

  • skip_exists (bool) – Skip if Realm already exist.

Returns

Keycloak server response (RealmRepresentation)

Return type

dict

update_realm(realm_name, payload)

Update a realm.

This will only update top level attributes and will ignore any user, role, or client information in the payload.

RealmRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmrepresentation

Parameters
  • realm_name (str) – Realm name (not the realm id)

  • payload (dict) – RealmRepresentation

Returns

Http response

Return type

dict

delete_realm(realm_name)

Delete a realm.

Parameters

realm_name (str) – Realm name (not the realm id)

Returns

Http response

Return type

dict

get_users(query=None)

Get all users.

Return a list of users, filtered according to query parameters

UserRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation

Parameters

query (dict) – Query parameters (optional)

Returns

users list

Return type

list

create_idp(payload)

Create an ID Provider.

IdentityProviderRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation

Param

payload: IdentityProviderRepresentation

Returns

Keycloak server response

Return type

dict

update_idp(idp_alias, payload)

Update an ID Provider.

IdentityProviderRepresentation https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_identity_providers_resource

Param

idp_alias: alias for IdP to update

Param

payload: The IdentityProviderRepresentation

Returns

Keycloak server response

Return type

dict

add_mapper_to_idp(idp_alias, payload)

Create an ID Provider.

IdentityProviderRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityprovidermapperrepresentation

Param

idp_alias: alias for Idp to add mapper in

Param

payload: IdentityProviderMapperRepresentation

Returns

Keycloak server response

Return type

dict

update_mapper_in_idp(idp_alias, mapper_id, payload)

Update an IdP mapper.

IdentityProviderMapperRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_update

Param

idp_alias: alias for Idp to fetch mappers

Param

mapper_id: Mapper Id to update

Param

payload: IdentityProviderMapperRepresentation

Returns

Http response

Return type

dict

get_idp_mappers(idp_alias)

Get IDP mappers.

Returns a list of ID Providers mappers

IdentityProviderMapperRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getmappers

Param

idp_alias: alias for Idp to fetch mappers

Returns

array IdentityProviderMapperRepresentation

Return type

list

get_idps()

Get IDPs.

Returns a list of ID Providers,

IdentityProviderRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_identityproviderrepresentation

Returns

array IdentityProviderRepresentation

Return type

list

delete_idp(idp_alias)

Delete an ID Provider.

Param

idp_alias: idp alias name

Returns

Keycloak server response

Return type

dict

create_user(payload, exist_ok=False)

Create a new user.

Username must be unique

UserRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation

Parameters
  • payload (dict) – UserRepresentation

  • exist_ok (bool) – If False, raise KeycloakGetError if username already exists. Otherwise, return existing user ID.

Returns

UserRepresentation

Return type

dict

users_count(query=None)

Count users.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_users_resource

Parameters

query (dict) – (dict) Query parameters for users count

Returns

counter

Return type

int

get_user_id(username)

Get internal keycloak user id from username.

This is required for further actions against this user.

UserRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation

Parameters

username (str) – id in UserRepresentation

Returns

user_id

Return type

str

get_user(user_id)

Get representation of the user.

UserRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userrepresentation

Parameters

user_id (str) – User id

Returns

UserRepresentation

get_user_groups(user_id, brief_representation=True)

Get user groups.

Returns a list of groups of which the user is a member

Parameters
  • user_id (str) – User id

  • brief_representation (bool) – whether to omit attributes in the response

Returns

user groups list

Return type

list

update_user(user_id, payload)

Update the user.

Parameters
  • user_id (str) – User id

  • payload (dict) – UserRepresentation

Returns

Http response

Return type

bytes

delete_user(user_id)

Delete the user.

Parameters

user_id (str) – User id

Returns

Http response

Return type

bytes

set_user_password(user_id, password, temporary=True)

Set up a password for the user.

If temporary is True, the user will have to reset the temporary password next time they log in.

https://www.keycloak.org/docs-api/18.0/rest-api/#_users_resource https://www.keycloak.org/docs-api/18.0/rest-api/#_credentialrepresentation

Parameters
  • user_id (str) – User id

  • password (str) – New password

  • temporary (bool) – True if password is temporary

Returns

Response

Return type

dict

get_credentials(user_id)

Get user credentials.

Returns a list of credential belonging to the user.

CredentialRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation

Param

user_id: user id

Returns

Keycloak server response (CredentialRepresentation)

Return type

dict

delete_credential(user_id, credential_id)

Delete credential of the user.

CredentialRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_credentialrepresentation

Param

user_id: user id

Param

credential_id: credential id

Returns

Keycloak server response (ClientRepresentation)

Return type

bytes

user_logout(user_id)

Log out the user.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_logout

Parameters

user_id (str) – User id

Returns

Keycloak server response

Return type

bytes

user_consents(user_id)

Get consents granted by the user.

UserConsentRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_userconsentrepresentation

Parameters

user_id (str) – User id

Returns

List of UserConsentRepresentations

Return type

list

get_user_social_logins(user_id)

Get user social logins.

Returns a list of federated identities/social logins of which the user has been associated with :param user_id: User id :type user_id: str :returns: Federated identities list :rtype: list

add_user_social_login(user_id, provider_id, provider_userid, provider_username)

Add a federated identity / social login provider to the user.

Parameters
  • user_id (str) – User id

  • provider_id (str) – Social login provider id

  • provider_userid (str) – userid specified by the provider

  • provider_username (str) – username specified by the provider

Returns

Keycloak server response

Return type

bytes

delete_user_social_login(user_id, provider_id)

Delete a federated identity / social login provider from the user.

Parameters
  • user_id (str) – User id

  • provider_id (str) – Social login provider id

Returns

Keycloak server response

Return type

bytes

send_update_account(user_id, payload, client_id=None, lifespan=None, redirect_uri=None)

Send an update account email to the user.

An email contains a link the user can click to perform a set of required actions.

Parameters
  • user_id (str) – User id

  • payload (list) – A list of actions for the user to complete

  • client_id (str) – Client id (optional)

  • lifespan (int) – Number of seconds after which the generated token expires (optional)

  • redirect_uri (str) – The redirect uri (optional)

Returns

Keycloak server response

Return type

bytes

send_verify_email(user_id, client_id=None, redirect_uri=None)

Send a update account email to the user.

An email contains a link the user can click to perform a set of required actions.

Parameters
  • user_id (str) – User id

  • client_id (str) – Client id (optional)

  • redirect_uri (str) – Redirect uri (optional)

Returns

Keycloak server response

Return type

bytes

get_sessions(user_id)

Get sessions associated with the user.

UserSessionRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation

Parameters

user_id (str) – Id of user

Returns

UserSessionRepresentation

Return type

dict

get_server_info()

Get themes, social providers, auth providers, and event listeners available on this server.

ServerInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation

Returns

ServerInfoRepresentation

Return type

dict

get_groups(query=None)

Get groups.

Returns a list of groups belonging to the realm

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters

query (dict) – Additional query options

Returns

array GroupRepresentation

Return type

list

get_group(group_id)

Get group by id.

Returns full group details

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters

group_id (str) – The group id

Returns

Keycloak server response (GroupRepresentation)

Return type

dict

get_subgroups(group, path)

Get subgroups.

Utility function to iterate through nested group structures

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters
  • group (dict) – group (GroupRepresentation)

  • path (str) – group path (string)

Returns

Keycloak server response (GroupRepresentation)

Return type

dict

get_group_members(group_id, query=None)

Get members by group id.

Returns group members

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_userrepresentation

Parameters
Returns

Keycloak server response (UserRepresentation)

Return type

list

get_group_by_path(path, search_in_subgroups=False)

Get group id based on name or path.

A straight name or path match with a top-level group will return first. Subgroups are traversed, the first to match path (or name with path) is returned.

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters
  • path (str) – group path

  • search_in_subgroups (bool) – True if want search in the subgroups

Returns

Keycloak server response (GroupRepresentation)

Return type

dict

create_group(payload, parent=None, skip_exists=False)

Create a group in the Realm.

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters
  • payload (dict) – GroupRepresentation

  • parent (str) – parent group’s id. Required to create a sub-group.

  • skip_exists (bool) – If true then do not raise an error if it already exists

Returns

Group id for newly created group or None for an existing group

Return type

str

update_group(group_id, payload)

Update group, ignores subgroups.

GroupRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/#_grouprepresentation

Parameters
  • group_id (str) – id of group

  • payload (dict) – GroupRepresentation with updated information.

Returns

Http response

Return type

bytes

group_set_permissions(group_id, enabled=True)

Enable/Disable permissions for a group.

Cannot delete group if disabled

Parameters
  • group_id (str) – id of group

  • enabled (bool) – Enabled flag

Returns

Keycloak server response

Return type

bytes

group_user_add(user_id, group_id)

Add user to group (user_id and group_id).

Parameters
  • user_id (str) – id of user

  • group_id (str) – id of group to add to

Returns

Keycloak server response

Return type

bytes

group_user_remove(user_id, group_id)

Remove user from group (user_id and group_id).

Parameters
  • user_id (str) – id of user

  • group_id (str) – id of group to remove from

Returns

Keycloak server response

Return type

bytes

delete_group(group_id)

Delete a group in the Realm.

Parameters

group_id (str) – id of group to delete

Returns

Keycloak server response

Return type

bytes

get_clients()

Get clients.

Returns a list of clients belonging to the realm

ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response (ClientRepresentation)

Return type

list

get_client(client_id)

Get representation of the client.

ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Parameters

client_id (str) – id of client (not client-id)

Returns

Keycloak server response (ClientRepresentation)

Return type

dict

get_client_id(client_id)

Get internal keycloak client id from client-id.

This is required for further actions against this client.

Parameters

client_id (str) – clientId in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

client_id (uuid as string)

Return type

str

get_client_authz_settings(client_id)

Get authorization json from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

dict

create_client_authz_resource(client_id, payload, skip_exists=False)

Create resources of client.

Parameters
Returns

Keycloak server response

Return type

bytes

get_client_authz_resources(client_id)

Get resources from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

dict

create_client_authz_role_based_policy(client_id, payload, skip_exists=False)

Create role-based policy of client.

Payload example:

payload={
    "type": "role",
    "logic": "POSITIVE",
    "decisionStrategy": "UNANIMOUS",
    "name": "Policy-1",
    "roles": [
        {
        "id": id
        }
    ]
}
Parameters
Returns

Keycloak server response

Return type

bytes

create_client_authz_resource_based_permission(client_id, payload, skip_exists=False)

Create resource-based permission of client.

Payload example:

payload={
    "type": "resource",
    "logic": "POSITIVE",
    "decisionStrategy": "UNANIMOUS",
    "name": "Permission-Name",
    "resources": [
        resource_id
    ],
    "policies": [
        policy_id
    ]
Parameters
Returns

Keycloak server response

Return type

bytes

get_client_authz_scopes(client_id)

Get scopes from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

list

get_client_authz_permissions(client_id)

Get permissions from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

list

get_client_authz_policies(client_id)

Get policies from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

list

get_client_service_account_user(client_id)

Get service account user from client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

UserRepresentation

Return type

dict

create_client(payload, skip_exists=False)

Create a client.

ClientRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Parameters
  • skip_exists (bool) – If true then do not raise an error if client already exists

  • payload (dict) – ClientRepresentation

Returns

Client ID

Return type

str

update_client(client_id, payload)

Update a client.

Parameters
  • client_id (str) – Client id

  • payload (dict) – ClientRepresentation

Returns

Http response

Return type

bytes

delete_client(client_id)

Get representation of the client.

ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Parameters

client_id (str) – keycloak client id (not oauth client-id)

Returns

Keycloak server response (ClientRepresentation)

Return type

bytes

get_client_installation_provider(client_id, provider_id)

Get content for given installation provider.

Related documentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clients_resource

Possible provider_id list available in the ServerInfoRepresentation#clientInstallations https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_serverinforepresentation

Parameters
  • client_id (str) – Client id

  • provider_id (str) – provider id to specify response format

Returns

Installation providers

Return type

list

get_realm_roles(brief_representation=True)

Get all roles for the realm or client.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters

brief_representation (bool) – whether to omit role attributes in the response

Returns

Keycloak server response (RoleRepresentation)

Return type

list

get_realm_role_members(role_name, query=None)

Get role members of realm by role name.

Parameters
Returns

Keycloak Server Response (UserRepresentation)

Return type

list

get_client_roles(client_id, brief_representation=True)

Get all roles for the client.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_id (str) – id of client (not client-id)

  • brief_representation (bool) – whether to omit role attributes in the response

Returns

Keycloak server response (RoleRepresentation)

Return type

list

get_client_role(client_id, role_name)

Get client role id by name.

This is required for further actions with this role.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_id (str) – id of client (not client-id)

  • role_name (str) – role’s name (not id!)

Returns

role_id

Return type

str

get_client_role_id(client_id, role_name)

Get client role id by name.

This is required for further actions with this role.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_id (str) – id of client (not client-id)

  • role_name (str) – role’s name (not id!)

Returns

role_id

Return type

str

create_client_role(client_role_id, payload, skip_exists=False)

Create a client role.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_role_id (str) – id of client (not client-id)

  • payload (dict) – RoleRepresentation

  • skip_exists (bool) – If true then do not raise an error if client role already exists

Returns

Client role name

Return type

str

add_composite_client_roles_to_role(client_role_id, role_name, roles)

Add composite roles to client role.

Parameters
  • client_role_id (str) – id of client (not client-id)

  • role_name (str) – The name of the role

  • roles (list) – roles list or role (use RoleRepresentation) to be updated

Returns

Keycloak server response

Return type

bytes

update_client_role(client_role_id, role_name, payload)

Update a client role.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_role_id (str) – id of client (not client-id)

  • role_name (str) – role’s name (not id!)

  • payload (dict) – RoleRepresentation

Returns

Keycloak server response

Return type

bytes

delete_client_role(client_role_id, role_name)

Delete a client role.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters
  • client_role_id (str) – id of client (not client-id)

  • role_name (str) – role’s name (not id!)

Returns

Keycloak server response

Return type

bytes

assign_client_role(user_id, client_id, roles)

Assign a client role to a user.

Parameters
  • user_id (str) – id of user

  • client_id (str) – id of client (not client-id)

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

bytes

get_client_role_members(client_id, role_name, **query)

Get members by client role.

Parameters
Returns

Keycloak server response (UserRepresentation)

Return type

list

get_client_role_groups(client_id, role_name, **query)

Get group members by client role.

Parameters
Returns

Keycloak server response

Return type

list

create_realm_role(payload, skip_exists=False)

Create a new role for the realm or client.

Parameters
  • payload (dict) – The role (use RoleRepresentation)

  • skip_exists (bool) – If true then do not raise an error if realm role already exists

Returns

Realm role name

Return type

str

get_realm_role(role_name)

Get realm role by role name.

RoleRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_rolerepresentation

Parameters

role_name (str) – role’s name, not id!

Returns

role

Return type

dict

update_realm_role(role_name, payload)

Update a role for the realm by name.

Parameters
  • role_name (str) – The name of the role to be updated

  • payload (dict) – The role (use RoleRepresentation)

Returns

Keycloak server response

Return type

bytes

delete_realm_role(role_name)

Delete a role for the realm by name.

Parameters

role_name (str) – The role name

Returns

Keycloak server response

Return type

bytes

add_composite_realm_roles_to_role(role_name, roles)

Add composite roles to the role.

Parameters
  • role_name (str) – The name of the role

  • roles (list) – roles list or role (use RoleRepresentation) to be updated

Returns

Keycloak server response

Return type

bytes

remove_composite_realm_roles_to_role(role_name, roles)

Remove composite roles from the role.

Parameters
  • role_name (str) – The name of the role

  • roles (list) – roles list or role (use RoleRepresentation) to be removed

Returns

Keycloak server response

Return type

bytes

get_composite_realm_roles_of_role(role_name)

Get composite roles of the role.

Parameters

role_name (str) – The name of the role

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

assign_realm_roles_to_client_scope(client_id, roles)

Assign realm roles to a client’s scope.

Parameters
  • client_id (str) – id of client (not client-id)

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

dict

delete_realm_roles_of_client_scope(client_id, roles)

Delete realm roles of a client’s scope.

Parameters
  • client_id (str) – id of client (not client-id)

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

dict

get_realm_roles_of_client_scope(client_id)

Get all realm roles for a client’s scope.

Parameters

client_id (str) – id of client (not client-id)

Returns

Keycloak server response (array RoleRepresentation)

Return type

dict

assign_client_roles_to_client_scope(client_id, client_roles_owner_id, roles)

Assign client roles to a client’s scope.

Parameters
  • client_id (str) – id of client (not client-id) who is assigned the roles

  • client_roles_owner_id (str) – id of client (not client-id) who has the roles

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

dict

delete_client_roles_of_client_scope(client_id, client_roles_owner_id, roles)

Delete client roles of a client’s scope.

Parameters
  • client_id (str) – id of client (not client-id) who is assigned the roles

  • client_roles_owner_id (str) – id of client (not client-id) who has the roles

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

dict

get_client_roles_of_client_scope(client_id, client_roles_owner_id)

Get all client roles for a client’s 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

assign_realm_roles(user_id, roles)

Assign realm roles to a user.

Parameters
  • user_id (str) – id of user

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

bytes

delete_realm_roles_of_user(user_id, roles)

Delete realm roles of a user.

Parameters
  • user_id (str) – id of user

  • roles (list) – roles list or role (use RoleRepresentation)

Returns

Keycloak server response

Return type

bytes

get_realm_roles_of_user(user_id)

Get all realm roles for a user.

Parameters

user_id (str) – id of user

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

get_available_realm_roles_of_user(user_id)

Get all available (i.e. unassigned) realm roles for a user.

Parameters

user_id (str) – id of user

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

get_composite_realm_roles_of_user(user_id, brief_representation=True)

Get all composite (i.e. implicit) realm roles for a user.

Parameters
  • user_id (str) – id of user

  • brief_representation (bool) – whether to omit role attributes in the response

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

assign_group_realm_roles(group_id, roles)

Assign realm roles to a group.

Parameters
  • group_id (str) – id of group

  • roles (list) – roles list or role (use GroupRoleRepresentation)

Returns

Keycloak server response

Return type

bytes

delete_group_realm_roles(group_id, roles)

Delete realm roles of a group.

Parameters
  • group_id (str) – id of group

  • roles (list) – roles list or role (use GroupRoleRepresentation)

Returns

Keycloak server response

Return type

bytes

get_group_realm_roles(group_id, brief_representation=True)

Get all realm roles for a group.

Parameters
  • group_id (str) – id of the group

  • brief_representation (bool) – whether to omit role attributes in the response

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

assign_group_client_roles(group_id, client_id, roles)

Assign client roles to a group.

Parameters
  • group_id (str) – id of group

  • client_id (str) – id of client (not client-id)

  • roles (list) – roles list or role (use GroupRoleRepresentation)

Returns

Keycloak server response

Return type

bytes

get_group_client_roles(group_id, client_id)

Get client roles of a group.

Parameters
  • group_id (str) – id of group

  • client_id (str) – id of client (not client-id)

Returns

Keycloak server response

Return type

list

delete_group_client_roles(group_id, client_id, roles)

Delete client roles of a group.

Parameters
  • group_id (str) – id of group

  • client_id (str) – id of client (not client-id)

  • roles (list) – roles list or role (use GroupRoleRepresentation)

Returns

Keycloak server response (array RoleRepresentation)

Return type

bytes

get_client_roles_of_user(user_id, client_id)

Get all client roles for a user.

Parameters
  • user_id (str) – id of user

  • client_id (str) – id of client (not client-id)

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

get_available_client_roles_of_user(user_id, client_id)

Get available client role-mappings for a user.

Parameters
  • user_id (str) – id of user

  • client_id (str) – id of client (not client-id)

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

get_composite_client_roles_of_user(user_id, client_id, brief_representation=False)

Get composite client role-mappings for a user.

Parameters
  • user_id (str) – id of user

  • client_id (str) – id of client (not client-id)

  • brief_representation (bool) – whether to omit attributes in the response

Returns

Keycloak server response (array RoleRepresentation)

Return type

list

_get_client_roles_of_user(client_level_role_mapping_url, user_id, client_id, **params)

Get client roles of a single user helper.

Parameters
  • client_level_role_mapping_url (str) – Url for the client role mapping

  • user_id (str) – User id

  • client_id (str) – Client id

  • params (dict) – Additional parameters

Returns

Client roles of a user

Return type

list

delete_client_roles_of_user(user_id, client_id, roles)

Delete client roles from a user.

Parameters
  • user_id (str) – id of user

  • client_id (str) – id of client containing role (not client-id)

  • roles (list) – roles list or role to delete (use RoleRepresentation)

Returns

Keycloak server response

Return type

bytes

get_authentication_flows()

Get authentication flows.

Returns all flow details

AuthenticationFlowRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation

Returns

Keycloak server response (AuthenticationFlowRepresentation)

Return type

list

get_authentication_flow_for_id(flow_id)

Get one authentication flow by it’s id.

Returns all flow details

AuthenticationFlowRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation

Parameters

flow_id (str) – the id of a flow NOT it’s alias

Returns

Keycloak server response (AuthenticationFlowRepresentation)

Return type

dict

create_authentication_flow(payload, skip_exists=False)

Create a new authentication flow.

AuthenticationFlowRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation

Parameters
  • payload (dict) – AuthenticationFlowRepresentation

  • skip_exists (bool) – Do not raise an error if authentication flow already exists

Returns

Keycloak server response (RoleRepresentation)

Return type

bytes

copy_authentication_flow(payload, flow_alias)

Copy existing authentication flow under a new name.

The new name is given as ‘newName’ attribute of the passed payload.

Parameters
  • payload (dict) – JSON containing ‘newName’ attribute

  • flow_alias (str) – the flow alias

Returns

Keycloak server response (RoleRepresentation)

Return type

bytes

delete_authentication_flow(flow_id)

Delete authentication flow.

AuthenticationInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationinforepresentation

Parameters

flow_id (str) – authentication flow id

Returns

Keycloak server response

Return type

bytes

get_authentication_flow_executions(flow_alias)

Get authentication flow executions.

Returns all execution steps

Parameters

flow_alias (str) – the flow alias

Returns

Response(json)

Return type

list

update_authentication_flow_executions(payload, flow_alias)

Update an authentication flow execution.

AuthenticationExecutionInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation

Parameters
  • payload (dict) – AuthenticationExecutionInfoRepresentation

  • flow_alias (str) – The flow alias

Returns

Keycloak server response

Return type

bytes

get_authentication_flow_execution(execution_id)

Get authentication flow execution.

AuthenticationExecutionInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation

Parameters

execution_id (str) – the execution ID

Returns

Response(json)

Return type

dict

create_authentication_flow_execution(payload, flow_alias)

Create an authentication flow execution.

AuthenticationExecutionInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation

Parameters
  • payload (dict) – AuthenticationExecutionInfoRepresentation

  • flow_alias (str) – The flow alias

Returns

Keycloak server response

Return type

bytes

delete_authentication_flow_execution(execution_id)

Delete authentication flow execution.

AuthenticationExecutionInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationexecutioninforepresentation

Parameters

execution_id (str) – keycloak client id (not oauth client-id)

Returns

Keycloak server response (json)

Return type

bytes

create_authentication_flow_subflow(payload, flow_alias, skip_exists=False)

Create a new sub authentication flow for a given authentication flow.

AuthenticationFlowRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticationflowrepresentation

Parameters
  • payload (dict) – AuthenticationFlowRepresentation

  • flow_alias (str) – The flow alias

  • skip_exists (bool) – Do not raise an error if authentication flow already exists

Returns

Keycloak server response (RoleRepresentation)

Return type

bytes

get_authenticator_providers()

Get authenticator providers list.

Returns

Authenticator providers

Return type

list

get_authenticator_provider_config_description(provider_id)

Get authenticator’s provider configuration description.

AuthenticatorConfigInfoRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfiginforepresentation

Parameters

provider_id (str) – Provider Id

Returns

AuthenticatorConfigInfoRepresentation

Return type

dict

get_authenticator_config(config_id)

Get authenticator configuration.

Returns all configuration details.

Parameters

config_id (str) – Authenticator config id

Returns

Response(json)

Return type

dict

update_authenticator_config(payload, config_id)

Update an authenticator configuration.

AuthenticatorConfigRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authenticatorconfigrepresentation

Parameters
  • payload (dict) – AuthenticatorConfigRepresentation

  • config_id (str) – Authenticator config id

Returns

Response(json)

Return type

bytes

delete_authenticator_config(config_id)

Delete a authenticator configuration.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_authentication_management_resource

Parameters

config_id (str) – Authenticator config id

Returns

Keycloak server Response

Return type

bytes

sync_users(storage_id, action)

Trigger user sync from provider.

Parameters
  • storage_id (str) – The id of the user storage provider

  • action (str) – Action can be “triggerFullSync” or “triggerChangedUsersSync”

Returns

Keycloak server response

Return type

bytes

get_client_scopes()

Get client scopes.

Get representation of the client scopes for the realm where we are connected to https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes

Returns

Keycloak server response Array of (ClientScopeRepresentation)

Return type

list

get_client_scope(client_scope_id)

Get client scope.

Get representation of the client scopes for the realm where we are connected to https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes

Parameters

client_scope_id (str) – The id of the client scope

Returns

Keycloak server response (ClientScopeRepresentation)

Return type

dict

get_client_scope_by_name(client_scope_name)

Get client scope by name.

Get representation of the client scope identified by the client scope name.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes :param client_scope_name: (str) Name of the client scope :type client_scope_name: str :returns: ClientScopeRepresentation or None :rtype: dict

create_client_scope(payload, skip_exists=False)

Create a client scope.

ClientScopeRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientscopes

Parameters
  • payload (dict) – ClientScopeRepresentation

  • skip_exists (bool) – If true then do not raise an error if client scope already exists

Returns

Client scope id

Return type

str

update_client_scope(client_scope_id, payload)

Update a client scope.

ClientScopeRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource

Parameters
  • client_scope_id (str) – The id of the client scope

  • payload (dict) – ClientScopeRepresentation

Returns

Keycloak server response (ClientScopeRepresentation)

Return type

bytes

delete_client_scope(client_scope_id)

Delete existing client scope.

ClientScopeRepresentation: https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_client_scopes_resource

Parameters

client_scope_id (str) – The id of the client scope

Returns

Keycloak server response

Return type

bytes

get_mappers_from_client_scope(client_scope_id)

Get a list of all mappers connected to the client scope.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource :param client_scope_id: Client scope id :type client_scope_id: str :returns: Keycloak server response (ProtocolMapperRepresentation) :rtype: list

add_mapper_to_client_scope(client_scope_id, payload)

Add a mapper to a client scope.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper

Parameters
  • client_scope_id (str) – The id of the client scope

  • payload (dict) – ProtocolMapperRepresentation

Returns

Keycloak server Response

Return type

bytes

delete_mapper_from_client_scope(client_scope_id, protocol_mapper_id)

Delete a mapper from a client scope.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_delete_mapper

Parameters
  • client_scope_id (str) – The id of the client scope

  • protocol_mapper_id (str) – Protocol mapper id

Returns

Keycloak server Response

Return type

bytes

update_mapper_in_client_scope(client_scope_id, protocol_mapper_id, payload)

Update an existing protocol mapper in a client scope.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocol_mappers_resource

Parameters
  • client_scope_id (str) – The id of the client scope

  • protocol_mapper_id (str) – The id of the protocol mapper which exists in the client scope and should to be updated

  • payload (dict) – ProtocolMapperRepresentation

Returns

Keycloak server Response

Return type

bytes

get_default_default_client_scopes()

Get default default client scopes.

Return list of default default client scopes

Returns

Keycloak server response

Return type

list

delete_default_default_client_scope(scope_id)

Delete default default client scope.

Parameters

scope_id (str) – default default client scope id

Returns

Keycloak server response

Return type

list

add_default_default_client_scope(scope_id)

Add default default client scope.

Parameters

scope_id (str) – default default client scope id

Returns

Keycloak server response

Return type

bytes

get_default_optional_client_scopes()

Get default optional client scopes.

Return list of default optional client scopes

Returns

Keycloak server response

Return type

list

delete_default_optional_client_scope(scope_id)

Delete default optional client scope.

Parameters

scope_id (str) – default optional client scope id

Returns

Keycloak server response

Return type

bytes

add_default_optional_client_scope(scope_id)

Add default optional client scope.

Parameters

scope_id (str) – default optional client scope id

Returns

Keycloak server response

Return type

bytes

get_mappers_from_client(client_id)

List of all client mappers.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_protocolmapperrepresentation

Parameters

client_id (str) – Client id

Returns

KeycloakServerResponse (list of ProtocolMapperRepresentation)

Return type

list

add_mapper_to_client(client_id, payload)

Add a mapper to a client.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_create_mapper

Parameters
  • client_id (str) – The id of the client

  • payload (dict) – ProtocolMapperRepresentation

Returns

Keycloak server Response

Return type

bytes

update_client_mapper(client_id, mapper_id, payload)

Update client mapper.

Parameters
  • client_id (str) – The id of the client

  • mapper_id (str) – The id of the mapper to be deleted

  • payload (dict) – ProtocolMapperRepresentation

Returns

Keycloak server response

Return type

bytes

remove_client_mapper(client_id, client_mapper_id)

Remove a mapper from the client.

https://www.keycloak.org/docs-api/15.0/rest-api/index.html#_protocol_mappers_resource

Parameters
  • client_id (str) – The id of the client

  • client_mapper_id (str) – The id of the mapper to be deleted

Returns

Keycloak server response

Return type

bytes

generate_client_secrets(client_id)

Generate a new secret for the client.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_regeneratesecret

Parameters

client_id (str) – id of client (not client-id)

Returns

Keycloak server response (ClientRepresentation)

Return type

bytes

get_client_secrets(client_id)

Get representation of the client secrets.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsecret

Parameters

client_id (str) – id of client (not client-id)

Returns

Keycloak server response (ClientRepresentation)

Return type

list

get_components(query=None)

Get components.

Return a list of components, filtered according to query parameters

ComponentRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation

Parameters

query (dict) – Query parameters (optional)

Returns

components list

Return type

list

create_component(payload)

Create a new component.

ComponentRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation

Parameters

payload (dict) – ComponentRepresentation

Returns

Component id

Return type

str

get_component(component_id)

Get representation of the component.

Parameters

component_id – Component id

ComponentRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_componentrepresentation

Parameters

component_id (str) – Id of the component

Returns

ComponentRepresentation

Return type

dict

update_component(component_id, payload)

Update the component.

Parameters
Returns

Http response

Return type

bytes

delete_component(component_id)

Delete the component.

Parameters

component_id (str) – Component id

Returns

Http response

Return type

bytes

get_keys()

Get keys.

Return a list of keys, filtered according to query parameters

KeysMetadataRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_key_resource

Returns

keys list

Return type

list

get_events(query=None)

Get events.

Return a list of events, filtered according to query parameters

EventRepresentation array https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_eventrepresentation

Parameters

query (dict) – Additional query parameters

Returns

events list

Return type

list

set_events(payload)

Set realm events configuration.

RealmEventsConfigRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_realmeventsconfigrepresentation

Parameters

payload (dict) – Payload object for the events configuration

Returns

Http response

Return type

bytes

raw_get(*args, **kwargs)

Call connection.raw_get.

If auto_refresh is set for get and access_token is expired, it will refresh the token and try get once more.

Parameters
  • args (tuple) – Additional arguments

  • kwargs (dict) – Additional keyword arguments

Returns

Response

Return type

Response

raw_post(*args, **kwargs)

Call connection.raw_post.

If auto_refresh is set for post and access_token is expired, it will refresh the token and try post once more.

Parameters
  • args (tuple) – Additional arguments

  • kwargs (dict) – Additional keyword arguments

Returns

Response

Return type

Response

raw_put(*args, **kwargs)

Call connection.raw_put.

If auto_refresh is set for put and access_token is expired, it will refresh the token and try put once more.

Parameters
  • args (tuple) – Additional arguments

  • kwargs (dict) – Additional keyword arguments

Returns

Response

Return type

Response

raw_delete(*args, **kwargs)

Call connection.raw_delete.

If auto_refresh is set for delete and access_token is expired, it will refresh the token and try delete once more.

Parameters
  • args (tuple) – Additional arguments

  • kwargs (dict) – Additional keyword arguments

Returns

Response

Return type

Response

get_token()

Get admin token.

The admin token is then set in the token attribute.

refresh_token()

Refresh the token.

Raises

KeycloakPostError – In case the refresh token request failed.

get_client_all_sessions(client_id)

Get sessions associated with the client.

UserSessionRepresentation http://www.keycloak.org/docs-api/18.0/rest-api/index.html#_usersessionrepresentation

Parameters

client_id (str) – id of client

Returns

UserSessionRepresentation

Return type

list

get_client_sessions_stats()

Get current session count for all clients with active sessions.

https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_getclientsessionstats

Returns

Dict of clients and session count

Return type

dict

get_client_management_permissions(client_id)

Get management permissions for a client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response

Return type

list

update_client_management_permissions(payload, client_id)

Update management permissions for a client.

ManagementPermissionReference https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_managementpermissionreference

Payload example:

payload={
    "enabled": true
}
Parameters
Returns

Keycloak server response

Return type

bytes

get_client_authz_policy_scopes(client_id, policy_id)

Get scopes for a given policy.

Parameters
Returns

Keycloak server response

Return type

list

get_client_authz_policy_resources(client_id, policy_id)

Get resources for a given policy.

Parameters
Returns

Keycloak server response

Return type

list

get_client_authz_scope_permission(client_id, scope_id)

Get permissions for a given scope.

Parameters
Returns

Keycloak server response

Return type

list

update_client_authz_scope_permission(payload, client_id, scope_id)

Update permissions for a given scope.

Payload example:

payload={
    "id": scope_id,
    "name": "My Permission Name",
    "type": "scope",
    "logic": "POSITIVE",
    "decisionStrategy": "UNANIMOUS",
    "resources": [some_resource_id],
    "scopes": [some_scope_id],
    "policies": [some_policy_id],
}
Parameters
Returns

Keycloak server response

Return type

bytes

get_client_authz_client_policies(client_id)

Get policies for a given client.

Parameters

client_id (str) – id in ClientRepresentation https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation

Returns

Keycloak server response (RoleRepresentation)

Return type

list

create_client_authz_client_policy(payload, client_id)

Create a new policy for a given client.

Payload example:

payload={
    "type": "client",
    "logic": "POSITIVE",
    "decisionStrategy": "UNANIMOUS",
    "name": "My Policy",
    "clients": [other_client_id],
}
Parameters
Returns

Keycloak server response (RoleRepresentation)

Return type

bytes

get_composite_client_roles_of_group(client_id, group_id, brief_representation=True)

Get the composite client roles of the given group for the given client.

Parameters
  • client_id (str) – id of the client.

  • group_id (str) – id of the group.

  • brief_representation (bool) – whether to omit attributes in the response

Returns

the composite client roles of the group (list of RoleRepresentation).

Return type

list

get_role_client_level_children(client_id, role_id)

Get the child roles of which the given composite client role is composed of.

Parameters
  • client_id (str) – id of the client.

  • role_id (str) – id of the role.

Returns

the child roles (list of RoleRepresentation).

Return type

list

upload_certificate(client_id, certcont)

Upload a new certificate for the client.

Parameters
  • client_id (str) – id of the client.

  • certcont (str) – the content of the certificate.

Returns

dictionary {“certificate”: “<certcont>”}, where <certcont> is the content of the uploaded certificate.

Return type

dict

get_required_action_by_alias(action_alias)

Get a required action by its alias.

Parameters

action_alias (str) – the alias of the required action.

Returns

the required action (RequiredActionProviderRepresentation).

Return type

dict

get_required_actions()

Get the required actions for the realms.

Returns

the required actions (list of RequiredActionProviderRepresentation).

Return type

list

update_required_action(action_alias, payload)

Update a required action.

Parameters
  • action_alias (str) – the action alias.

  • payload (dict) – the new required action (RequiredActionProviderRepresentation).

Returns

empty dictionary.

Return type

dict

get_bruteforce_detection_status(user_id)

Get bruteforce detection status for user.

Parameters

user_id (str) – User id

Returns

Bruteforce status.

Return type

dict

clear_bruteforce_attempts_for_user(user_id)

Clear bruteforce attempts for user.

Parameters

user_id (str) – User id

Returns

empty dictionary.

Return type

dict

clear_all_bruteforce_attempts()

Clear bruteforce attempts for all users in realm.

Returns

empty dictionary.

Return type

dict

class keycloak.KeycloakOpenID(server_url, realm_name, client_id, client_secret_key=None, verify=True, custom_headers=None, proxies=None, timeout=60)[source]

Keycloak OpenID client.

Parameters
  • server_url – Keycloak server url

  • client_id – client id

  • realm_name – realm name

  • client_secret_key – client secret key

  • verify – True if want check connection SSL

  • 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

property client_id

Get client id.

Returns

Client id

Return type

str

property client_secret_key

Get the client secret key.

Returns

Client secret key

Return type

str

property realm_name

Get the realm name.

Returns

Realm name

Return type

str

property connection

Get connection.

Returns

Connection manager object

Return type

ConnectionManager

property authorization

Get authorization.

Returns

The authorization manager

Return type

Authorization

_add_secret_key(payload)

Add secret key if exists.

Parameters

payload (dict) – Payload

Returns

Payload with the secret key

Return type

dict

_build_name_role(role)

Build name of a role.

Parameters

role (str) – Role name

Returns

Role path

Return type

str

_token_info(token, method_token_info, **kwargs)

Getter for the token data.

Parameters
  • token (str) – Token

  • method_token_info (str) – Token info method to use

  • kwargs (dict) – Additional keyword arguments

Returns

Token info

Return type

dict

well_known()

Get the well_known object.

The most important endpoint to understand is the well-known configuration endpoint. It lists endpoints and other configuration options relevant to the OpenID Connect implementation in Keycloak.

Returns

It lists endpoints and other configuration options relevant

Return type

dict

auth_url(redirect_uri, scope='email', state='')

Get authorization URL endpoint.

Parameters
  • redirect_uri (str) – Redirect url to receive oauth code

  • scope (str) – Scope of authorization request, split with the blank space

  • state (str) – State will be returned to the redirect_uri

Returns

Authorization URL Full Build

Return type

str

token(username='', password='', grant_type=['password'], code='', redirect_uri='', totp=None, **extra)

Retrieve user token.

The token endpoint is used to obtain tokens. Tokens can either be obtained by exchanging an authorization code or by supplying credentials directly depending on what flow is used. The token endpoint is also used to obtain new access tokens when they expire.

http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint

Parameters
  • username (str) – Username

  • password (str) – Password

  • grant_type (str) – Grant type

  • code (str) – Code

  • redirect_uri (str) – Redirect URI

  • totp (int) – Time-based one-time password

  • extra (dict) – Additional extra arguments

Returns

Keycloak token

Return type

dict

refresh_token(refresh_token, grant_type=['refresh_token'])

Refresh the user token.

The token endpoint is used to obtain tokens. Tokens can either be obtained by exchanging an authorization code or by supplying credentials directly depending on what flow is used. The token endpoint is also used to obtain new access tokens when they expire.

http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint

Parameters
  • refresh_token (str) – Refresh token from Keycloak

  • grant_type (str) – Grant type

Returns

New token

Return type

dict

exchange_token(token: str, client_id: str, audience: str, subject: str, requested_token_type: str = 'urn:ietf:params:oauth:token-type:refresh_token', scope: str = '') dict

Exchange user token.

Use a token to obtain an entirely different token. See https://www.keycloak.org/docs/latest/securing_apps/index.html#_token-exchange

Parameters
  • token (str) – Access token

  • client_id (str) – Client id

  • audience (str) – Audience

  • subject (str) – Subject

  • requested_token_type (str) – Token type specification

  • scope (str) – Scope

Returns

Exchanged token

Return type

dict

userinfo(token)

Get the user info object.

The userinfo endpoint returns standard claims about the authenticated user, and is protected by a bearer token.

http://openid.net/specs/openid-connect-core-1_0.html#UserInfo

Parameters

token (str) – Access token

Returns

Userinfo object

Return type

dict

logout(refresh_token)

Log out the authenticated user.

Parameters

refresh_token (str) – Refresh token from Keycloak

Returns

Keycloak server response

Return type

dict

certs()

Get certificates.

The certificate endpoint returns the public keys enabled by the realm, encoded as a JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled for verifying tokens.

https://tools.ietf.org/html/rfc7517

Returns

Certificates

Return type

dict

public_key()

Retrieve the public key.

The public key is exposed by the realm page directly.

Returns

The public key

Return type

str

entitlement(token, resource_server_id)

Get entitlements from the token.

Client applications can use a specific endpoint to obtain a special security token called a requesting party token (RPT). This token consists of all the entitlements (or permissions) for a user as a result of the evaluation of the permissions and authorization policies associated with the resources being requested. With an RPT, client applications can gain access to protected resources at the resource server.

Parameters
  • token (str) – Access token

  • resource_server_id (str) – Resource server ID

Returns

Entitlements

Return type

dict

introspect(token, rpt=None, token_type_hint=None)

Introspect the user token.

The introspection endpoint is used to retrieve the active state of a token. It is can only be invoked by confidential clients.

https://tools.ietf.org/html/rfc7662

Parameters
  • token (str) – Access token

  • rpt (str) – Requesting party token

  • token_type_hint (str) – Token type hint

Returns

Token info

Return type

dict

Raises

KeycloakRPTNotFound – In case of RPT not specified

decode_token(token, key, algorithms=['RS256'], **kwargs)

Decode user token.

A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. This specification also defines a JWK Set JSON data structure that represents a set of JWKs. Cryptographic algorithms and identifiers for use with this specification are described in the separate JSON Web Algorithms (JWA) specification and IANA registries established by that specification.

https://tools.ietf.org/html/rfc7517

Parameters
  • token (str) – Keycloak token

  • key (str) – Decode key

  • algorithms (list[str]) – Algorithms to use for decoding

  • kwargs (dict) – Keyword arguments

Returns

Decoded token

Return type

dict

load_authorization_config(path)

Load Keycloak settings (authorization).

Parameters

path (str) – settings file (json)

get_policies(token, method_token_info='introspect', **kwargs)

Get policies by user token.

Parameters
  • token (str) – User token

  • method_token_info (str) – Method for token info decoding

  • kwargs (dict) – Additional keyword arguments

Returns

Policies

Return type

dict

Raises
get_permissions(token, method_token_info='introspect', **kwargs)

Get permission by user token.

Parameters
  • token (str) – user token

  • method_token_info (str) – Decode token method

  • kwargs (dict) – parameters for decode

Returns

permissions list

Return type

list

Raises
uma_permissions(token, permissions='')

Get UMA permissions by user token with requested permissions.

The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be invoked by confidential clients.

http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint

Parameters
  • token (str) – user token

  • permissions (str) – list of uma permissions list(resource:scope) requested by the user

Returns

Keycloak server response

Return type

dict

has_uma_access(token, permissions)

Determine whether user has uma permissions with specified user token.

Parameters
  • token (str) – user token

  • permissions (str) – list of uma permissions (resource:scope)

Returns

Authentication status

Return type

AuthStatus

Raises