Composable authentication sources for FastAPI: bring your own validator, combine multiple schemes, correct OpenAPI by construction
Project description
FastAPI MultiAuth
Composable authentication sources for FastAPI: bring your own validator, combine multiple schemes with MultiAuth, and get correct OpenAPI documentation by construction.
Documentation: https://fastapi-multiauth.d3vyce.fr
Source Code: https://github.com/d3vyce/fastapi-multiauth
fastapi-multiauth is the composable layer between the raw primitives of fastapi.security and opinionated frameworks like fastapi-users or AuthX. You provide the validator; the library handles extraction, scheme combination, and OpenAPI declaration. No database coupling, no user model, no ready-made login routes.
Installation
uv add fastapi-multiauth
Optional extras pull in their dependencies on demand:
uv add "fastapi-multiauth[jwt]" # JWTValidator (PyJWT)
uv add "fastapi-multiauth[oauth]" # OAuth 2.0 / OIDC helpers (httpx-oauth)
uv add "fastapi-multiauth[jwt,oauth]"
Quick Start
from fastapi import FastAPI, Security
from fastapi_multiauth import HTTPBearerAuth, APIKeyCookieAuth, MultiAuth, UnauthorizedError
async def validate_token(token: str) -> dict:
user = await lookup_user_by_token(token)
if user is None:
raise UnauthorizedError()
return user
async def validate_session(value: str) -> dict:
return await lookup_user_by_session(value)
bearer = HTTPBearerAuth(validate_token, prefix="user_")
session = APIKeyCookieAuth("session", validate_session, secret_key="...")
# Accept either an API token or a web session on the same route.
auth = MultiAuth(bearer, session)
app = FastAPI()
@app.get("/me")
async def me(user=Security(auth)):
return user
Features
- BYO validator: every source wraps a sync or async callable you provide; the library never touches your user model or database.
MultiAuth: try several sources in order on a single route (e.g. web session cookie + API bearer token), with all schemes documented in OpenAPI.- Built-in sources: covering the standard
fastapi.securityschemes:HTTPBearerAuth: bearer tokens with optional Stripe-styleuser_/org_prefixes to route different token types to different validators, plusgenerate_token()for secure token creation.APIKeyCookieAuth: cookie sessions with optional HMAC-SHA256 signing (via itsdangerous), embedded expiry, and key rotation.APIKeyHeaderAuth:X-API-Key-style schemes, withAPIKeyQueryAuthfor legacy clients that can only pass a query parameter.HTTPBasicAuth:validator(username, password)withWWW-Authenticaterealm support.
- Token hashing helpers:
hash_token/verify_token_hashpackage the "store the hash, never the token" pattern with constant-time comparison. - JWT validation (
fastapi-multiauth[jwt]extra):JWTValidatorforHTTPBearerAuth: HS256 or provider JWKS (Keycloak/Auth0/Entra/Authentik) with TTL caching and rotation-awarekidrefresh,aud/iss/expchecks, configurable scope claims, and aclaims_to_identityhook. - Security scopes:
Security(auth, scopes=[...])forwards the declared scopes to validators that accept ascopesparameter. - Correct HTTP semantics: 401 with
WWW-Authenticatechallenges (RFC 7235) and 403 viaForbiddenError. - OAuth 2.0 / OIDC helpers (
fastapi-multiauth[oauth]extra): async discovery with TTL caching, HTTPS enforcement, CSRF-protectedstateencoding, PKCE (S256), and code exchange delegated to httpx-oauth.
Comparison
An honest map of where fastapi-multiauth sits. It is the composable layer between the raw primitives of fastapi.security and opinionated user frameworks. If you want ready-made /register//login routes and a user model, you want a different tool.
fastapi.security (native) |
fastapi-multiauth | fastapi-users | AuthX | Authlib | |
|---|---|---|---|---|---|
| Credential extraction + OpenAPI | ✅ | ✅ | ✅ | ✅ | ➖ |
| Bring-your-own validator | manual | ✅ | ❌ (own user model) | partial | manual |
| Multiple schemes on one route | manual | ✅ MultiAuth |
❌ | ❌ | ❌ |
| Signed cookie sessions (rotation, name-binding) | ❌ | ✅ | ✅ (own format) | ✅ (JWT in cookie) | ❌ |
| Opaque API tokens (prefixes, hash helpers) | ❌ | ✅ | ✅ (DB-backed) | ❌ | ❌ |
| JWT validation (HS + JWKS) | ❌ | ✅ JWTValidator |
✅ | ✅ | ✅ |
| JWT issuance / refresh | ❌ | ❌ | ✅ | ✅ | ✅ |
| Scope enforcement (fail-closed) | manual | ✅ | partial | ✅ | manual |
| OAuth login client helpers (PKCE, state) | ❌ | ✅ | ✅ (per-provider) | ❌ | ✅ (full client) |
| OAuth2/OIDC server | ❌ | ❌ | ❌ | ❌ | ✅ |
| User model, register/login/reset routes | ❌ | ❌ | ✅ | ❌ | ❌ |
| Database coupling | none | none | SQLAlchemy/Beanie | none | none |
| Maintenance status | active | active | maintenance mode | active | active |
When to pick what:
fastapi.securityalone: one scheme, simple validator, no sessions. The primitives are fine, this library just saves you the boilerplate around them.- fastapi-multiauth: you own the user store and just need request-time auth: bring your own validator, combine several schemes on one route with
MultiAuth, validate opaque tokens or JWTs, and get correct OpenAPI for free. No user model, no issued tokens, no database coupling. - fastapi-users: you want batteries included (user table, password reset, verified-email flow) and accept its user model. Note it is in maintenance mode.
- AuthX: your session model is "login issues a JWT pair, refresh endpoint rotates it". This library validates JWTs but will never issue them.
- Authlib: you are building an OAuth2/OIDC server, or need a full-featured OAuth client beyond the login flow.
FAQ
Can I use it with sync validators?
Yes, every source accepts sync or async callables (including callable class instances) and awaits them correctly.
Why don't my route scopes show in Swagger UI?
The OpenAPI specification only allows scope lists on oauth2/openIdConnect schemes; for http/apiKey schemes the array must be empty. Enforcement happens at runtime regardless; see Usage → Security scopes.
License
This project is licensed under the MIT License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_multiauth-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_multiauth-0.1.0.tar.gz
- Upload date:
- Size: 21.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c1256bd276293e307b47abca82d90c4eb8e3ae4ec4f9b4310e95956178524dbc
|
|
| MD5 |
193313ff21d1a89d270f485e64429f74
|
|
| BLAKE2b-256 |
5ad6b81277ebb6d6b6b62385ba13ddaeb31edac03fe8f5bd8cf4d12fe6a379a6
|
Provenance
The following attestation bundles were made for fastapi_multiauth-0.1.0.tar.gz:
Publisher:
build-release.yml on d3vyce/fastapi-multiauth
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_multiauth-0.1.0.tar.gz -
Subject digest:
c1256bd276293e307b47abca82d90c4eb8e3ae4ec4f9b4310e95956178524dbc - Sigstore transparency entry: 1871721335
- Sigstore integration time:
-
Permalink:
d3vyce/fastapi-multiauth@2fc4e2b655b8500a0285a0676a04319fd76b8817 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/d3vyce
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build-release.yml@2fc4e2b655b8500a0285a0676a04319fd76b8817 -
Trigger Event:
release
-
Statement type:
File details
Details for the file fastapi_multiauth-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_multiauth-0.1.0-py3-none-any.whl
- Upload date:
- Size: 31.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1c2226d3bd48d27960531b6743a80ecec43c4b7a067dd9998aee745b035a60cc
|
|
| MD5 |
0d79ba49f7570563a6917ef5a0eab6c2
|
|
| BLAKE2b-256 |
511dba21b2a4b9e5a2a34a099400f2f67cbfbf8ffc22235b5e276b094fc4eac3
|
Provenance
The following attestation bundles were made for fastapi_multiauth-0.1.0-py3-none-any.whl:
Publisher:
build-release.yml on d3vyce/fastapi-multiauth
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
fastapi_multiauth-0.1.0-py3-none-any.whl -
Subject digest:
1c2226d3bd48d27960531b6743a80ecec43c4b7a067dd9998aee745b035a60cc - Sigstore transparency entry: 1871721473
- Sigstore integration time:
-
Permalink:
d3vyce/fastapi-multiauth@2fc4e2b655b8500a0285a0676a04319fd76b8817 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/d3vyce
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build-release.yml@2fc4e2b655b8500a0285a0676a04319fd76b8817 -
Trigger Event:
release
-
Statement type: