Axioms FastAPI
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
-
ModuleNotFoundError: No module named 'axioms_fastapi'
cause The `axioms-fastapi` package or its dependencies are not installed in the current Python environment.fixRun `pip install axioms-fastapi` to install the library. -
HTTPException 401: Unauthorized
cause The provided access token is missing, invalid, expired, or does not have the necessary scopes/claims, or the OIDC configuration is incorrect.fixCheck the OIDC client configuration (issuer, audience, client_id). Ensure a valid Bearer token is sent in the 'Authorization' header. Inspect the token's claims (e.g., using jwt.io) to verify its validity, expiration, and audience against your `oidc_config`. -
KeyError: 'preferred_username' (or similar for other token claims)
cause The decoded JWT token payload does not contain the expected claim, or the claim name differs from what the application expects.fixReview your OIDC provider's configuration to ensure it's issuing the desired claims (e.g., `preferred_username`, `email`). Adjust your application code to use available claims (e.g., `user.get('sub')` for the subject ID, which is always present).
Warnings
- breaking The library is currently in `0.0.x` versions, which implies that API stability is not guaranteed. Minor version bumps (e.g., from 0.0.12 to 0.0.13) might introduce breaking changes without a major version increment.
- gotcha Incorrect OIDC configuration (e.g., `issuer_url`, `client_id`, `client_secret`, `audience`) is a common source of authentication failures. Misconfiguration can lead to `401 Unauthorized` errors or token validation issues.
- gotcha If `python-jose` fails to validate tokens with errors like 'Signature has no ECI parameter', it often indicates an issue with the public key, signing algorithm, or token structure.
Install
-
pip install axioms-fastapi
Imports
- OIDCConfig
from axioms_fastapi import OIDCConfig
- AxiomsAuth
from axioms_fastapi import AxiomsAuth
- Depends
from fastapi import Depends
Quickstart
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.