keycloak.keycloak_openid
Keycloak OpenID module.
The module contains mainly the implementation of KeycloakOpenID class, the main class to handle authentication and token manipulation.
Classes
Keycloak OpenID client. |
Module Contents
- class keycloak.keycloak_openid.KeycloakOpenID(server_url, realm_name, client_id, client_secret_key=None, verify=True, custom_headers=None, proxies=None, timeout=60, cert=None, max_retries=1)[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 – 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 (int) – The total number of times to retry HTTP requests.
- property client_secret_key[source]
Get the client secret key.
- Returns:
Client secret key
- Return type:
str
- _add_secret_key(payload)[source]
Add secret key if exists.
- Parameters:
payload (dict) – Payload
- Returns:
Payload with the secret key
- Return type:
dict
- _build_name_role(role)[source]
Build name of a role.
- Parameters:
role (str) – Role name
- Returns:
Role path
- Return type:
str
- _token_info(token, method_token_info, **kwargs)[source]
Getter for the token data.
- Parameters:
token (str) – Token
method_token_info (str) – Token info method to use
kwargs (dict) – Additional keyword arguments passed to the decode_token method
- Returns:
Token info
- Return type:
dict
- well_known()[source]
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='', nonce='')[source]
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
nonce (str) – Associates a Client session with an ID Token to mitigate replay attacks
- Returns:
Authorization URL Full Build
- Return type:
str
- token(username='', password='', grant_type='password', code='', redirect_uri='', totp=None, scope='openid', **extra)[source]
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
scope (str) – Scope, defaults to openid
extra (dict) – Additional extra arguments
- Returns:
Keycloak token
- Return type:
dict
- refresh_token(refresh_token, grant_type='refresh_token')[source]
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, audience: str | None = None, subject: str | None = None, subject_token_type: str | None = None, subject_issuer: str | None = None, requested_issuer: str | None = None, requested_token_type: str = 'urn:ietf:params:oauth:token-type:refresh_token', scope: str = 'openid') dict [source]
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
audience (str) – Audience
subject (str) – Subject
subject_token_type (Optional[str]) – Token Type specification
subject_issuer (Optional[str]) – Issuer
requested_issuer (Optional[str]) – Issuer
requested_token_type (str) – Token type specification
scope (str) – Scope, defaults to openid
- Returns:
Exchanged token
- Return type:
dict
- userinfo(token)[source]
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)[source]
Log out the authenticated user.
- Parameters:
refresh_token (str) – Refresh token from Keycloak
- Returns:
Keycloak server response
- Return type:
dict
- certs()[source]
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()[source]
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)[source]
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)[source]
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
- static _verify_token(token, key: jwcrypto.jwk.JWK | jwcrypto.jwk.JWKSet | None, **kwargs)[source]
Decode and optionally validate a token.
- Parameters:
token (str) – The token to verify
key (Union[jwk.JWK, jwk.JWKSet, None]) – Which key should be used for validation. If not provided, the validation is not performed and the token is implicitly valid.
kwargs (dict) – Additional keyword arguments for jwcrypto’s JWT object
- Returns:
Decoded token
- decode_token(token, validate: bool = True, **kwargs)[source]
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
validate (bool) – Determines whether the token should be validated with the public key. Defaults to True.
kwargs (dict) – Additional keyword arguments for jwcrypto’s JWT object
- Returns:
Decoded token
- Return type:
dict
- load_authorization_config(path)[source]
Load Keycloak settings (authorization).
- Parameters:
path (str) – settings file (json)
- get_policies(token, method_token_info='introspect', **kwargs)[source]
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:
KeycloakAuthorizationConfigError – In case of bad authorization configuration
KeycloakInvalidTokenError – In case of bad token
- get_permissions(token, method_token_info='introspect', **kwargs)[source]
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:
KeycloakAuthorizationConfigError – In case of bad authorization configuration
KeycloakInvalidTokenError – In case of bad token
- uma_permissions(token, permissions='')[source]
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)[source]
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:
- Raises:
KeycloakAuthenticationError – In case of failed authentication
KeycloakPostError – In case of failed request to Keycloak
- register_client(token: str, payload: dict)[source]
Create a client.
ClientRepresentation: https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
- Parameters:
token (str) – Initial access token
payload (dict) – ClientRepresentation
- Returns:
Client Representation
- Return type:
dict
- device(scope: str = '')[source]
Get device authorization grant.
The device endpoint is used to obtain a user code verification and user authentication. The response contains a device_code, user_code, verification_uri, verification_uri_complete, expires_in (lifetime in seconds for device_code and user_code), and polling interval. Users can either follow the verification_uri and enter the user_code or follow the verification_uri_complete. After authenticating with valid credentials, users can obtain tokens using the “urn:ietf:params:oauth:grant-type:device_code” grant_type and the device_code.
https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow https://github.com/keycloak/keycloak-community/blob/main/design/oauth2-device-authorization-grant.md#how-to-try-it
- Parameters:
scope (str) – Scope of authorization request, split with the blank space
- Returns:
Device Authorization Response
- Return type:
dict
- update_client(token: str, client_id: str, payload: dict)[source]
Update a client.
ClientRepresentation: https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
- Parameters:
token (str) – registration access token
client_id (str) – Keycloak client id
payload (dict) – ClientRepresentation
- Returns:
Client Representation
- Return type:
dict
- async _a_token_info(token, method_token_info, **kwargs)[source]
Asynchronous getter for the token data.
- Parameters:
token (str) – Token
method_token_info (str) – Token info method to use
kwargs (dict) – Additional keyword arguments passed to the decode_token method
- Returns:
Token info
- Return type:
dict
- async a_well_known()[source]
Get the well_known object asynchronously.
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
- async a_auth_url(redirect_uri, scope='email', state='', nonce='')[source]
Get authorization URL endpoint asynchronously.
- 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
nonce (str) – Associates a Client session with an ID Token to mitigate replay attacks
- Returns:
Authorization URL Full Build
- Return type:
str
- async a_token(username='', password='', grant_type='password', code='', redirect_uri='', totp=None, scope='openid', **extra)[source]
Retrieve user token asynchronously.
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
scope (str) – Scope, defaults to openid
extra (dict) – Additional extra arguments
- Returns:
Keycloak token
- Return type:
dict
- async a_refresh_token(refresh_token, grant_type='refresh_token')[source]
Refresh the user token asynchronously.
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
- async a_exchange_token(token: str, audience: str | None = None, subject: str | None = None, subject_token_type: str | None = None, subject_issuer: str | None = None, requested_issuer: str | None = None, requested_token_type: str = 'urn:ietf:params:oauth:token-type:refresh_token', scope: str = 'openid') dict [source]
Exchange user token asynchronously.
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
audience (str) – Audience
subject (str) – Subject
subject_token_type (Optional[str]) – Token Type specification
subject_issuer (Optional[str]) – Issuer
requested_issuer (Optional[str]) – Issuer
requested_token_type (str) – Token type specification
scope (str) – Scope, defaults to openid
- Returns:
Exchanged token
- Return type:
dict
- async a_userinfo(token)[source]
Get the user info object asynchronously.
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
- async a_logout(refresh_token)[source]
Log out the authenticated user asynchronously.
- Parameters:
refresh_token (str) – Refresh token from Keycloak
- Returns:
Keycloak server response
- Return type:
dict
- async a_certs()[source]
Get certificates asynchronously.
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
- async a_public_key()[source]
Retrieve the public key asynchronously.
The public key is exposed by the realm page directly.
- Returns:
The public key
- Return type:
str
- async a_entitlement(token, resource_server_id)[source]
Get entitlements from the token asynchronously.
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
- async a_introspect(token, rpt=None, token_type_hint=None)[source]
Introspect the user token asynchronously.
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
- async a_decode_token(token, validate: bool = True, **kwargs)[source]
Decode user token asynchronously.
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
validate (bool) – Determines whether the token should be validated with the public key. Defaults to True.
kwargs (dict) – Additional keyword arguments for jwcrypto’s JWT object
- Returns:
Decoded token
- Return type:
dict
- async a_load_authorization_config(path)[source]
Load Keycloak settings (authorization) asynchronously.
- Parameters:
path (str) – settings file (json)
- async a_get_policies(token, method_token_info='introspect', **kwargs)[source]
Get policies by user token asynchronously.
- 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:
KeycloakAuthorizationConfigError – In case of bad authorization configuration
KeycloakInvalidTokenError – In case of bad token
- async a_get_permissions(token, method_token_info='introspect', **kwargs)[source]
Get permission by user token asynchronously.
- Parameters:
token (str) – user token
method_token_info (str) – Decode token method
kwargs (dict) – parameters for decode
- Returns:
permissions list
- Return type:
list
- Raises:
KeycloakAuthorizationConfigError – In case of bad authorization configuration
KeycloakInvalidTokenError – In case of bad token
- async a_uma_permissions(token, permissions='')[source]
Get UMA permissions by user token with requested permissions asynchronously.
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
- async a_has_uma_access(token, permissions)[source]
Determine whether user has uma permissions with specified user token asynchronously.
- Parameters:
token (str) – user token
permissions (str) – list of uma permissions (resource:scope)
- Returns:
Authentication status
- Return type:
- Raises:
KeycloakAuthenticationError – In case of failed authentication
KeycloakPostError – In case of failed request to Keycloak
- async a_register_client(token: str, payload: dict)[source]
Create a client asynchronously.
ClientRepresentation: https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
- Parameters:
token (str) – Initial access token
payload (dict) – ClientRepresentation
- Returns:
Client Representation
- Return type:
dict
- async a_device(scope: str = '')[source]
Get device authorization grant asynchronously.
The device endpoint is used to obtain a user code verification and user authentication. The response contains a device_code, user_code, verification_uri, verification_uri_complete, expires_in (lifetime in seconds for device_code and user_code), and polling interval. Users can either follow the verification_uri and enter the user_code or follow the verification_uri_complete. After authenticating with valid credentials, users can obtain tokens using the “urn:ietf:params:oauth:grant-type:device_code” grant_type and the device_code.
https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow https://github.com/keycloak/keycloak-community/blob/main/design/oauth2-device-authorization-grant.md#how-to-try-it
- Parameters:
scope (str) – Scope of authorization request, split with the blank space
- Returns:
Device Authorization Response
- Return type:
dict
- async a_update_client(token: str, client_id: str, payload: dict)[source]
Update a client asynchronously.
ClientRepresentation: https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
- Parameters:
token (str) – registration access token
client_id (str) – Keycloak client id
payload (dict) – ClientRepresentation
- Returns:
Client Representation
- Return type:
dict