HTTPX Auth

0.23.1 · active · verified Sun Apr 12

httpx-auth is a Python library that provides a collection of authentication classes designed for use with the HTTPX client library. It supports various authentication schemes, including OAuth2 (Authorization Code, PKCE, Client Credentials, Resource Owner Password Credentials, Implicit flows), Okta, Microsoft Entra ID (formerly Azure AD), and AWS Signature Version 4. While a 1.0.0 release is pending HTTPX's own 1.0.0, the library is considered stable and is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `OAuth2AuthorizationCode` with HTTPX. It sets up an authentication object with placeholder OAuth2 URLs and a client ID. When `client.get()` is called, `httpx-auth` will manage the OAuth2 Authorization Code flow, typically by opening a browser for user interaction to obtain an access token, which is then used for the request. Remember to replace placeholder URLs and client ID with your actual values and configure the `redirect_uri` for your OAuth2 application if running locally.

import httpx
import os
from httpx_auth import OAuth2AuthorizationCode

# In a real application, these would come from environment variables or a secure configuration
# For this example, we use placeholders. Replace with your actual OAuth2 application details.
CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID", "your_client_id")
AUTHORIZATION_URL = os.environ.get("OAUTH_AUTH_URL", "https://example.com/oauth/authorize")
TOKEN_URL = os.environ.get("OAUTH_TOKEN_URL", "https://example.com/oauth/token")

try:
    auth = OAuth2AuthorizationCode(
        client_id=CLIENT_ID,
        authorization_url=AUTHORIZATION_URL,
        token_url=TOKEN_URL,
        # For local development, redirect_uri would typically be a local callback URL.
        # httpx-auth will start a local server to capture the redirect.
        # Ensure this matches what's configured for your OAuth2 client application.
        # Example: redirect_uri="http://localhost:8000/callback", port=8000
    )

    with httpx.Client() as client:
        # The first request will trigger the OAuth2 flow:
        # 1. Opens a browser for user consent.
        # 2. User grants permission, browser redirects to redirect_uri.
        # 3. httpx-auth captures the code and exchanges it for a token.
        # 4. The request to the protected resource is then made with the acquired token.
        response = client.get("https://api.example.com/protected-resource", auth=auth)
        response.raise_for_status()
        print(f"Successfully authenticated and fetched data: {response.json()}")

except httpx.HTTPStatusError as e:
    print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")
except httpx.RequestError as e:
    print(f"An error occurred while making the request: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →