PyKeycloak is a library for working with Keycloak that provides asynchronous methods for authentication, token management, and permission handling.
- Sanitized logging: Automatically hide sensitive data in request/response logs.
- Httpx-powered: Gain full control using standard httpx client configuration.
- Rich Request/Response handling: Access a comprehensive list of parameters and detailed response fields.
- Flexible Data Access: Easily work with both raw data and structured representations.
- Environment-based config: Quick setup using environment variables.
For local development to install dependencies, use the following command:
make installThe library can be used in 3 different ways:
- Make requests directly through the client
- Use the provider to get response with content
- Use the service to get either raw responses or Representation objects corresponding to the data received from Keycloak
KEYCLOAK_ACCESS_TOKEN=
KEYCLOAK_REALM_NAME=
KEYCLOAK_REALM_OTAGO_SERVICE_CLIENT_UUID= # !!! OTAGO_SERVICE_CLIENT - is the keyword when from_env(realm_name='otago_service_client')
KEYCLOAK_REALM_OTAGO_SERVICE_CLIENT_ID=
KEYCLOAK_REALM_OTAGO_SERVICE_CLIENT_SECRET=
KEYCLOAK_REALM_OTAGO_SSO_CLIENT_UUID= # !!! OTAGO_SSO - is the keyword when from_env(realm_name='otago_sso')
KEYCLOAK_REALM_OTAGO_SSO_CLIENT_ID=
KEYCLOAK_REALM_OTAGO_SSO_CLIENT_SECRET=
KEYCLOAK_BASE_URL=
KEYCLOAK_HTTPX_CLIENT_PARAMS_HTTP1=
KEYCLOAK_HTTPX_CLIENT_PARAMS_HTTP2=
KEYCLOAK_HTTPX_CLIENT_PARAMS_FOLLOW_REDIRECTS=
KEYCLOAK_HTTPX_CLIENT_PARAMS_TRUST_ENV=
KEYCLOAK_HTTPX_CLIENT_CLIENT_PARAMS_TIMEOUT=
KEYCLOAK_HTTPX_CLIENT_PARAMS_MAX_CONNECTIONS=
KEYCLOAK_HTTPX_CLIENT_PARAMS_MAX_KEEPALIVE_CONNECTIONS=
KEYCLOAK_HTTPX_CLIENT_PARAMS_KEEPALIVE_EXPIRY=
KEYCLOAK_HTTPX_CLIENT_PARAMS_MAX_REDIRECTS=
KEYCLOAK_HTTPX_CLIENT_PARAMS_DEFAULT_ENCODING=utf-8
KEYCLOAK_MAX_ROWS_QUERY_LIMIT=1000
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_VERIFY=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_CERT=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_TRUST_ENV=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_HTTP1=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_HTTP2=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_RETRIES=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_PROXY=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_UDS=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_LOCAL_ADDRESSES=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_MAX_CONNECTIONS=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_KEEPALIVE_EXPIRY=
KEYCLOAK_HTTPX_HTTP_TRANSPORT_HTTP_MAX_KEEPALIVE_CONNECTIONS=
DATA_SANITIZER_EXTRA_SENSITIVE_KEYS=
DATA_SANITIZER_DEBUG=False
UMA_PERMISSIONS_CHUNK_SIZE=1 # when there are thousands of permissions have to be checked-
TokenIntrospectionPayload- Payload for token introspection containing the token. -
RTPIntrospectionPayload- Payload for token introspection inherited fromTokenIntrospectionPayload, containing the token type. -
ObtainTokenPayload- Base class for obtaining a token, containing the scope and grant type. -
UserCredentialsLoginPayload- Payload for user authentication containing username and password. -
ClientCredentialsLoginPayload- Payload for client authentication used to obtain a client token. -
RefreshTokenPayload- Payload for refreshing a token containing the refresh token. -
UMAAuthorizationPayload- Payload for UMA authorization containing audience, permissions, and other parameters.
KeycloakProviderAsync- Asynchronous provider for working with Keycloak that provides methods for authentication, token refresh, user information retrieval, logout, token introspection, device authentication, and certificate retrieval.
from pykeycloak.providers.providers import KeycloakInMemoryProviderAsync
from pykeycloak.core.realm import RealmClient
provider = KeycloakInMemoryProviderAsync(
realm="kc_realm",
realm_client=RealmClient.from_env(),
)AuthService - Service that provides methods for authentication, token refresh, user information retrieval, logout, token introspection, device authentication, and certificate retrieval.
from pykeycloak.services.services import AuthService
from pykeycloak.providers.providers import KeycloakInMemoryProviderAsync
from pykeycloak.core.realm import RealmClient
provider = KeycloakInMemoryProviderAsync(
realm="kc_realm",
realm_client=RealmClient.from_env(),
)
auth = AuthService(provider)UmaService - Service that provides a method for obtaining UMA permissions.
from pykeycloak.services.services import UmaService
from pykeycloak.providers.providers import KeycloakInMemoryProviderAsync
from pykeycloak.core.realm import RealmClient
provider = KeycloakInMemoryProviderAsync(
realm="kc_realm",
realm_client=RealmClient.from_env(),
)
uma = UmaService(provider)Representations duplicate the data from Keycloak documentation based on the actual values they return.
TokenRepresentation - Representation of a token containing information about the access token, expiration time, scope, and token type.
UserInfoRepresentation - Representation of user information containing user data such as first name, last name, email address, and other attributes.
RealmAccessRepresentation - Representation of realm access containing user roles in the realm.
IntrospectRepresentation - Representation of token introspection result containing token information such as audience, expiration time, token type, and other attributes.
RealmClient - Entity that stores realm data:
import os
from pykeycloak.core.realm import RealmClient
RealmClient.from_env()
# or
RealmClient(
client_id=os.getenv("KEYCLOAK_REALM_CLIENT_ID"),
client_uuid=os.getenv("KEYCLOAK_REALM_CLIENT_UUID"),
client_secret=os.getenv("KEYCLOAK_REALM_CLIENT_SECRET")
)Processes headers and request/response logs, hiding all critical information and marking it as hidden.
import os
from pykeycloak.core.sanitizer import SensitiveDataSanitizer
SensitiveDataSanitizer.from_env()
SensitiveDataSanitizer(
sensitive_keys=frozenset(os.getenv("EXTRA_SENSITIVE_KEYS", None))
)To get started, you need to initialize the client using environment variables:
To authenticate a user, use the user_login_async method:
from pykeycloak.providers.payloads import UserCredentialsLoginPayload
token = await auth_service.user_login_async(
payload=UserCredentialsLoginPayload(
username=username,
password=password,
))To refresh a token, use the refresh_token_async method:
from pykeycloak.providers.payloads import RefreshTokenPayload
refresh_token = await auth_service.refresh_token_async(
payload=RefreshTokenPayload(refresh_token=token.refresh_token)
)To introspect a token, use the introspect_async method:
from pykeycloak.providers.payloads import TokenIntrospectionPayload
introspect = await auth_service.introspect_token_async(
payload=TokenIntrospectionPayload(
token=refresh.auth_token,
)
)To retrieve UMA permissions, use the get_uma_permissions_async method:
from pykeycloak.providers.payloads import UMAAuthorizationPayload
permissions = await uma_service.get_uma_permissions_async(
access_token=token.auth_token, # user token
payload=UMAAuthorizationPayload(
audience=client.client_id,
permissions={'/otago/users': ['view']}
)
)To retrieve user information, use the get_user_info_async method:
user_info = await auth_service.get_user_info_async(
access_token=refresh.auth_token
)To log out, use the logout_async method:
await auth_service.logout_async(refresh.refresh_token)To retrieve certificates, use the get_certs_raw_async method:
certs = await auth_service.get_certs_raw_async()This project is licensed under the MIT License.