Skip to main content

FastAPI MultiAuth

Composable authentication sources for FastAPI: bring your own validator, combine multiple schemes with MultiAuth, and get correct OpenAPI documentation by construction.

CI codecov CodSpeed Badge ty uv Ruff Python 3.11+ License: MIT


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.security schemes:
    • HTTPBearerAuth: bearer tokens with optional Stripe-style user_/org_ prefixes to route different token types to different validators, plus generate_token() for secure token creation (bring your own token_generator to pick the token format).
    • APIKeyCookieAuth: cookie sessions with optional HMAC-SHA256 signing (via itsdangerous), embedded expiry, key rotation, and optional per-session ids so your app can list and revoke sessions individually.
    • APIKeyHeaderAuth: X-API-Key-style schemes, with APIKeyQueryAuth for legacy clients that can only pass a query parameter.
    • HTTPBasicAuth: validator(username, password) with WWW-Authenticate realm support.
    • OAuth2AuthorizationCodeBearerAuth, OAuth2PasswordBearerAuth, OpenIdConnectAuth: validate tokens an OAuth 2.0 / OIDC provider issued, and publish the scope catalogue so /docs offers a real Authorize dialog.
  • Token hashing helpers: hash_token/verify_token_hash package the "store the hash, never the token" pattern with constant-time comparison, and checksum_token_generator/verify_token_checksum add a GitHub-style CRC32 suffix that refuses typos before the lookup.
  • JWT validation (fastapi-multiauth[jwt] extra): JWTValidator for HTTPBearerAuth: HS256 or provider JWKS (Keycloak/Auth0/Entra/Authentik) with TTL caching and rotation-aware kid refresh, aud/iss/exp checks, configurable scope claims, and a claims_to_identity hook.
  • Security scopes: Security(auth, scopes=[...]) forwards the declared scopes to validators that accept a scopes parameter.
  • WebSocket routes: every source and MultiAuth guard @app.websocket routes too, refusing the handshake with the same 401/403.
  • Freshness / step-up auth: source.fresh(max_age=...) refuses a credential proven too long ago on the endpoints that can take over an account, with the RFC 9470 challenge that tells a client to re-authenticate. Signed cookies date themselves; anything else reads the instant off your identity. source.stepped_up(acr_values=[...], acr=...) asks for a stronger level instead, and composes with fresh() into one challenge; AuthenticationMethodReference names the RFC 8176 amr values.
  • Correct HTTP semantics: 401 with WWW-Authenticate challenges (RFC 7235) and 403 via ForbiddenError.
  • Security-event logging: every refusal is a WARNING under fastapi_multiauth.* with a reason code (invalid_signature, expired, stale, …) in extra, never the credential or the identity; silent until your app configures logging.
  • OAuth 2.0 / OIDC helpers (fastapi-multiauth[oauth] extra): async discovery with TTL caching, HTTPS enforcement, CSRF-protected state encoding, PKCE (S256), code exchange delegated to httpx-oauth, and OpenID Connect ID token validation with nonce and at_hash (plus the jwt extra).

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.security alone: 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.

Metadata

Release files for fastapi-multiauth 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-multiauth 0.8.0
File Size Uploaded Provenance Actions
fastapi_multiauth-0.8.0.tar.gz 41.1 kB With provenance Details for fastapi_multiauth-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-multiauth 0.8.0
File Interpreter ABI Platform Actions
fastapi_multiauth-0.8.0-py3-none-any.whl Python 3 none any Details for fastapi_multiauth-0.8.0-py3-none-any.whl

Total release size: 92.7 kB

Release files / fastapi_multiauth-0.8.0.tar.gz

Download URL fastapi_multiauth-0.8.0.tar.gz
Size 41.1 kB
Tags Source
SHA-256 checksum
How to use checksums
77110ba75d272b4e678c6f4fed36323f0929191c7994c1caf245ee2ce3734f5f
BLAKE2b-256 checksum
How to use checksums
4433600df35a257f78db989900c6604c57d59473fe9cd016ce1dc0269051f575
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.

Transparency log

Release files / fastapi_multiauth-0.8.0-py3-none-any.whl

Download URL fastapi_multiauth-0.8.0-py3-none-any.whl
Size 51.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e4239af89c48a5505ce2eba2d3caee99e748aa390ef24a24620a8f962c3f3e71
BLAKE2b-256 checksum
How to use checksums
abf0cfcb6ce486535880477d72b11448abdacfe1cd33d5990ba0b736aaa6cd35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.

Transparency log

Security for fastapi-multiauth 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_multiauth-0.8.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page