Axioms FastAPI

0.0.13 · active · verified Fri Apr 17

axioms-fastapi provides robust OAuth2/OIDC authentication and authorization for FastAPI APIs, simplifying integration with identity providers. It is currently at version 0.0.13 and sees minor, incremental releases, indicating active development with potential for API changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a FastAPI application with `axioms-fastapi` for OIDC authentication. It configures the OIDC provider using environment variables, initializes `AxiomsAuth`, and protects an endpoint using `Depends(axioms_auth.get_current_user)`. A public endpoint is also included for comparison. Remember to replace placeholder URLs and credentials with your actual OIDC provider details.

import os
from fastapi import FastAPI, Depends, HTTPException, status
from axioms_fastapi import OIDCConfig, AxiomsAuth

app = FastAPI()

# Configure OIDC using environment variables for sensitive data
# Replace with your actual OIDC provider details
oidc_config = OIDCConfig(
    issuer_url=os.environ.get('OIDC_ISSUER_URL', 'https://your-oidc-provider.com/realm'),
    client_id=os.environ.get('OIDC_CLIENT_ID', 'your-client-id'),
    client_secret=os.environ.get('OIDC_CLIENT_SECRET', 'your-client-secret'),
    audience=os.environ.get('OIDC_AUDIENCE', 'api://your-app') # Often the client_id or a specific identifier
)

# Initialize AxiomsAuth with the OIDC configuration
axioms_auth = AxiomsAuth(oidc_config)

@app.get("/protected")
async def protected_route(user: dict = Depends(axioms_auth.get_current_user)):
    """An endpoint protected by OIDC authentication."""
    # The 'user' object will contain decoded token claims if authentication is successful
    username = user.get('preferred_username', user.get('sub', 'anonymous'))
    return {"message": f"Hello, {username}! This is a protected route.", "user_info": user}

@app.get("/public")
async def public_route():
    """A public endpoint that does not require authentication."""
    return {"message": "This is a public route."}

# To run this app (requires uvicorn):
# 1. pip install uvicorn
# 2. Set environment variables:
#    export OIDC_ISSUER_URL="https://your-oidc-provider.com/auth/realms/master" # Example Keycloak
#    export OIDC_CLIENT_ID="your_api_client_id"
#    export OIDC_CLIENT_SECRET="your_client_secret"
#    export OIDC_AUDIENCE="account"
# 3. uvicorn your_file_name:app --reload
# Then access /docs to try it out.

view raw JSON →