H2O Python Clients Authentication Helpers

3.1.0 · active · verified Fri Apr 17

h2o-authn provides authentication helpers for H2O.ai Python clients, simplifying secure interactions with H2O AI Cloud and other services. It primarily focuses on managing and refreshing access tokens using various authentication flows, such as Client Credentials. The current version is 3.1.0, and the library maintains an active development pace with several releases per year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `h2o-authn` to obtain an access token using the Client Credentials flow. It fetches authentication details from environment variables (H2O_AUTHN_URI, H2O_AUTHN_CLIENT_ID, H2O_AUTHN_CLIENT_SECRET), initializes a `ClientCredentialsTokenProvider` with an `httpx.AsyncClient`, and then retrieves a token. It also shows wrapping the provider with `AuthCache` for automatic token caching and refreshing.

import os
import httpx
import asyncio
from h2o_authn import ClientCredentialsTokenProvider, AuthCache

async def authenticate_and_get_token():
    auth_url = os.environ.get("H2O_AUTHN_URI", "")
    client_id = os.environ.get("H2O_AUTHN_CLIENT_ID", "")
    client_secret = os.environ.get("H2O_AUTHN_CLIENT_SECRET", "")

    if not all([auth_url, client_id, client_secret]):
        print("Please set H2O_AUTHN_URI, H2O_AUTHN_CLIENT_ID, and H2O_AUTHN_CLIENT_SECRET environment variables.")
        return

    async with httpx.AsyncClient() as client:
        token_provider = ClientCredentialsTokenProvider(
            auth_url=auth_url,
            client_id=client_id,
            client_secret=client_secret,
            client=client,
        )

        # Optional: Wrap with AuthCache for token caching and refresh
        cached_token_provider = AuthCache(token_provider)

        try:
            token = await cached_token_provider.get_token()
            print(f"Successfully obtained token. Access Token (first 10 chars): {token.access_token[:10]}...")
            print(f"Token expires in: {token.expires_in} seconds")
        except Exception as e:
            print(f"Authentication failed: {e}")

if __name__ == "__main__":
    asyncio.run(authenticate_and_get_token())

view raw JSON →