python-keycloak

repository·master·Indexed 21 days ago

https://github.com/marcospereirampj/python-keycloak

A Python client library providing programmatic access to the Keycloak API. It supports OpenID Connect (OIDC) flows for user authentication and authorization, administrative operations via the KeycloakAdmin class for managing users, realms, and clients, and User-Managed Access (UMA) for fine-grained authorization. The library also supports asynchronous operations for non-blocking integration.

Tokens
19.1K
Snippets
65
Records
71
Agent score
69%

What's inside python-keycloak

  1. Quickstart with python-keycloak

    master

    The python-keycloak library provides integration for Keycloak using three primary patterns:

    1. OpenID Connect (OIDC): For client-side authentication and authorization flows.
    2. Admin API: For managing Keycloak resources (users, realms, clients, etc.) programmatically.
    3. UMA (User-Managed Access): For fine-grained authorization and resource management.

    Additionally, the library supports asynchronous operations for non-blocking integration.

  2. Run tests and linting checks with tox

    master

    The project uses tox to manage testing and linting workflows. Note that tox requires docker to be installed on your system, as it spins up a local Keycloak instance for integration testing to avoid excessive mocking.

    • Unit Tests: Run the test suite using the tests environment.
    • Linting & Formatting: Check if code adheres to flake8, black, and isort standards using the check environment.
    • Auto-formatting: Automatically apply isort and black formatting using the apply-check environment (note: flake8 errors must still be fixed manually).
    • Documentation: Verify that documentation builds without warnings using the docs environment.
    # Run unit tests
    tox -e tests
    
    # Run linting and formatting checks
    tox -e check
    
    # Automatically apply formatting (black and isort)
    tox -e apply-check
    
    # Check documentation for build warnings
    tox -e docs
  3. Initialize the KeycloakOpenID client

    master

    To interact with Keycloak using OpenID Connect, instantiate the KeycloakOpenID class.

    Important Note on server_url: For Keycloak versions older than 18, you must append /auth/ to the end of the server_url.

    Common parameters:

    • server_url: The base URL of your Keycloak server.
    • client_id: The ID of the client configured in Keycloak.
    • realm_name: The name of the realm.
    • client_secret_key: The client secret (required for confidential clients).
    • pool_maxsize: (Optional) Sets the connection pool size.
    from keycloak import KeycloakOpenID
    
    # Configure client
    # For versions older than 18 /auth/ must be added at the end of the server_url.
    keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/",
                                     client_id="example_client",
                                     realm_name="example_realm",
                                     client_secret_key="secret",
                                     pool_maxsize=15)
  4. Install python-keycloak manually from source

    master

    If you prefer to install from source, you can clone the repository or download the source code directly from GitHub. Once you have the source code locally, navigate to the root directory and install it into your site-packages using pip:

    git clone https://github.com/marcospereirampj/python-keycloak.git
    cd python-keycloak
    python -m pip install .
    git clone https://github.com/marcospereirampj/python-keycloak.git
    python -m pip install .
  5. Use KeycloakAdmin for administrative tasks

    master

    The KeycloakAdmin class allows you to perform administrative operations like managing users. It requires a KeycloakOpenIDConnection object for authentication.

    Setup Steps:

    1. Create a KeycloakOpenIDConnection providing server_url, admin credentials (username, password), realm_name (usually master for admin tasks), and client credentials.
    2. Pass the connection to KeycloakAdmin(connection=...).

    Key Operations:

    • create_user(user_details, exist_ok=True): Creates a new user. You can pass exist_ok=False to raise an exception if the username already exists. You can also include credentials in the user details dictionary to set a password immediately.
    from keycloak import KeycloakAdmin
    from keycloak import KeycloakOpenIDConnection
    
    keycloak_connection = KeycloakOpenIDConnection(
                            server_url="http://localhost:8080/",
                            username='example-admin',
                            password='secret',
                            realm_name="master",
                            user_realm_name="only_if_other_realm_than_master",
                            client_id="my_client",
                            client_secret_key="client-secret",
                            verify=True)
    
    keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
    
    # Add user with password
    new_user = keycloak_admin.create_user({
        "email": "example@example.com",
        "username": "example@example.com",
        "enabled": True,
        "firstName": "Example",
        "lastName": "Example",
        "credentials": [{"value": "secret", "type": "password"}]
    })
  6. Configure the KeycloakUMA client

    master

    To use User-Managed Access (UMA) features, initialize a KeycloakUMA instance by passing a configured KeycloakOpenIDConnection object to its connection parameter. The connection object requires server_url, realm_name, client_id, and client_secret_key.

    from keycloak import KeycloakOpenIDConnection
    from keycloak import KeycloakUMA
    
    keycloak_connection = KeycloakOpenIDConnection(
                            server_url="http://localhost:8080/",
                            realm_name="master",
                            client_id="my_client",
                            client_secret_key="client-secret")
    
    keycloak_uma = KeycloakUMA(connection=keycloak_connection)
  7. Perform OAuth2 Authorization Code Flow

    master

    The Authorization Code flow involves two steps: requesting the authorization URL and then exchanging the resulting code for an access token.

    1. Get Authorization URL

    Use auth_url() to generate the URL where you redirect the user to log in.

    2. Exchange Code for Token

    Once the user is redirected back to your redirect_uri with a code, use token() with grant_type='authorization_code' to retrieve the tokens.

    # 1. Get authorization URL
    auth_url = keycloak_openid.auth_url(
        redirect_uri="your_call_back_url",
        scope="email",
        state="your_state_info")
    
    # 2. Get access token with code
    access_token = keycloak_openid.token(
        grant_type='authorization_code',
        code='the_code_you_get_from_auth_url_callback',
        redirect_uri="your_call_back_url")
  8. Configure the Asynchronous Admin Client

    master

    To manage Keycloak users, realms, and clients asynchronously, use the KeycloakAdmin class. You can configure it by passing parameters directly to the constructor or by providing a KeycloakOpenIDConnection object for more advanced connection settings (like client credentials or SSL verification).

    from keycloak import KeycloakAdmin
    from keycloak import KeycloakOpenIDConnection
    
    # Option 1: Direct configuration
    admin = KeycloakAdmin(
        server_url="http://localhost:8080/",
        username='example-admin',
        password='secret',
        realm_name="master",
        user_realm_name="only_if_other_realm_than_master"
    )
    
    # Option 2: Using a connection object
    keycloak_connection = KeycloakOpenIDConnection(
        server_url="http://localhost:8080/",
        username='example-admin',
        password='secret',
        realm_name="master",
        user_realm_name="only_if_other_realm_than_master",
        client_id="my_client",
        client_secret_key="client-secret",
        verify=True
    )
    keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
  9. Configure the KeycloakAdmin client

    master

    To perform administrative tasks, you must instantiate a KeycloakAdmin client. You can configure it in two ways:

    1. Direct Configuration: Pass connection parameters directly to the KeycloakAdmin constructor.
    2. Connection Object: Pass an existing KeycloakOpenIDConnection instance to the KeycloakAdmin constructor. This is recommended for reusing connection settings.

    Common parameters include:

    • server_url: The base URL of your Keycloak server.
    • username / password: Credentials for the admin user.
    • realm_name: The realm you are operating in (e.g., master).
    • user_realm_name: The realm where the admin user resides (only if different from realm_name).
    • client_id / client_secret_key: Credentials if using a client-based authentication.
    • pool_maxsize: Maximum size of the connection pool.
    # Option 1: Direct Configuration
    admin = KeycloakAdmin(
        server_url="http://localhost:8080/",
        username='example-admin',
        password='secret',
        realm_name="master",
        user_realm_name="only_if_other_realm_than_master",
        pool_maxsize=20
    )
    
    # Option 2: Using a KeycloakOpenIDConnection object
    from keycloak import KeycloakAdmin
    from keycloak import KeycloakOpenIDConnection
    
    keycloak_connection = KeycloakOpenIDConnection(
        server_url="http://localhost:8080/",
        username='example-admin',
        password='secret',
        realm_name="master",
        user_realm_name="only_if_other_realm_than_master",
        client_id="my_client",
        client_secret_key="client-secret",
        pool_maxsize=25,
        verify=True
    )
    
    keycloak_admin = KeycloakAdmin(connection=keycloak_connection)
  10. Use KeycloakOpenID for OpenID Connect flows

    master

    The KeycloakOpenID class is used to interact with Keycloak using OpenID Connect protocols, such as obtaining authorization URLs, exchanging codes for tokens, and managing user sessions.

    Common tasks include:

    • Configuration: Initialize with server_url, client_id, realm_name, and client_secret_key.
    • Discovery: Use .well_known() to retrieve the OpenID configuration.
    • Authorization: Use .auth_url() to generate the URL for the OAuth authorization request.
    • Token Exchange: Use .token() with grant_type='authorization_code' to exchange a code for an access token.
    • Direct Authentication: Use .token(username, password) for resource owner password credentials.
    • Session Management: Use .refresh_token(), .userinfo(), and .logout() to manage the user lifecycle.
    from keycloak import KeycloakOpenID
    
    # Configure client
    keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
                                     client_id="example_client",
                                     realm_name="example_realm",
                                     client_secret_key="secret")
    
    # Get WellKnown
    config_well_known = keycloak_openid.well_known()
    
    # Get Code With Oauth Authorization Request
    auth_url = keycloak_openid.auth_url(
        redirect_uri="your_call_back_url",
        scope="email",
        state="your_state_info")
    
    # Get Access Token With Code
    access_token = keycloak_openid.token(
        grant_type='authorization_code',
        code='the_code_you_get_from_auth_url_callback',
        redirect_uri="your_call_back_url")
    
    # Get Token (Password Grant)
    token = keycloak_openid.token("user", "password")
    
    # Get Userinfo
    userinfo = keycloak_openid.userinfo(token['access_token'])
    
    # Refresh token
    token = keycloak_openid.refresh_token(token['refresh_token'])
    
    # Logout
    keycloak_openid.logout(token['refresh_token'])