fastauth
A modular, Pydantic-native, async-only authentication library for FastAPI.
pip install fastauth-py
from fastapi import FastAPI
from pydantic import SecretStr
from fastauth import FastAuth, FastAuthOptions
from fastauth.database import memory
from fastauth.options import CookieOptions
from fastauth import email_password
app_secret = "replace-me-with-a-secret-from-your-application-config"
options = FastAuthOptions(
secret_key=SecretStr(app_secret),
database=memory(),
cookie=CookieOptions(secure=False),
)
auth = FastAuth(options, plugins=[email_password()])
app = FastAPI(lifespan=auth.lifespan)
app.include_router(auth.router, prefix="/auth", tags=["auth"])
auth.add_middleware(app)
That's it. You now have /auth/sign-up/email, /auth/sign-in/email,
/auth/sign-out, /auth/get-session, /auth/verify-email,
/auth/forgot-password, /auth/reset-password, /auth/change-password,
/auth/set-password, /auth/verify-password, /auth/user,
/auth/delete-account, /auth/delete-account/request,
/auth/delete-account/confirm,
/auth/change-email/{request,confirm}, /auth/sessions (list / revoke /
revoke-others), /auth/refresh, /auth/health/live, and /auth/health/ready
wired into your FastAPI
application. Rate-limiting, account-lockout, and refresh tokens are part of
the router.
Direct include_router() integration lets your application choose the prefix,
tags, and global dependencies. auth.add_middleware(app) separately installs
FastAuth's exception handler, CSRF middleware, and security headers.
auth.as_asgi() provides a standalone app with both routes and middleware
already installed.
Why fastauth
Built deliberately for the modern Python web stack — FastAPI + Pydantic v2 + async-only + MongoDB or Postgres persistence:
- Pydantic v2 everywhere. Every public domain model, request body, and
response is a
BaseModel. Runtime wiring may use ordinary Python types internally, but the API boundary stays Pydantic-native. - Async-first. Authentication flows expose async APIs. CPU/memory-heavy
Argon2 work runs off the event loop with a bounded concurrency limit
(default 2 per hasher; configure
password.max_concurrent_operations). - Strict-typed.
pyright --strictpasses with 0 errors, 0 warnings.py.typedmarker ships with the wheel — your IDE and your CI get full type information. - Source-agnostic options.
FastAuthOptionsis a plainBaseModel. The framework never reads process-level configuration. You build config from your application settings object, vault client, parameter store, or test fixture and pass it in explicitly. - Plugins as first-class extension points. Seven built-in providers
(
email_password(),api_key(),jwt(),email_otp(),audit_logs(),openapi(),test_utils()) — each contributes endpoints, event handlers, lifecycle hooks, and rate-limit policies through a tightPluginABC. Write your own for OAuth providers, webhooks, custom MFA — whatever your app needs. - Capability-based storage protocols.
DatabaseAdaptercovers the core auth flows. Optional surfaces (ApiKeyStore,JwksKeyStore,AuditLogStore,RateLimitStore) are only required when you enable the matching plugin or database-backed feature. - Pure events. A single typed
EventBuscarries 19 concreteAuthEventsubclasses (UserSignedUp,UserEmailVerified,PasswordChanged,AccountLockedOut, …). Subscribe and react — send emails, ping Slack, write audit rows, whatever.
What's in the box
Auth flows
- Sign-up / sign-in / sign-out by email or username
- Email verification with anti-enumeration
- Password reset with anti-enumeration and session-wide revoke
- Authenticated change-password (keeps current session, revokes others)
- Authenticated profile update, set-password, verify-password, and account deletion with password or email-token verification
- Authenticated change-email with re-verification
- Refresh tokens with one-time-use rotation and family-revocation on reuse (OAuth 2.1-style theft detection)
- Multi-session management: list, revoke one, revoke-all-except-current
Sessions
- Database-backed sessions (revocable, with recorded IP/UA metadata) or JWT sessions (stateless, JWKS-signed). One config flag flips between them.
- JWKS with auto-generated keys, AES-GCM at-rest encryption with master-key
rotation support, and an opt-in
set-auth-jwtresponse header that attaches a JWT to every authenticated response. - Local key signing or plug in your own
KmsSigner(HSM, AWS KMS, GCP KMS, …) via a tiny Protocol. - JWT/JWKS crypto has not been independently audited. For high-stakes production deployments, use an external KMS/HSM signer and run your own security review before relying on local private-key storage.
Security
- Argon2id password hashing (configurable cost).
- Account lockout — HTTP 423 +
Retry-Afterafter 5 failed sign-ins in 15 min. - CSRF middleware — Origin/Referer validation on state-changing methods, bearer-only requests are exempt.
- Rate limiting with /64 IPv6-subnet bucketing, per-(IP, path) windowing, pluggable storage (memory, MongoDB, Postgres).
- Security headers — HSTS,
X-Frame-Options,X-Content-Type-Options,Referrer-Policyon by default; opt-inPermissions-Policyand CSP.
Plugins (each optional)
- email_password() — sign-up, sign-in, password reset, email verification, username requirements and changes, account management, refresh tokens, and session management.
- api_key() — create/verify/list/update/delete API keys with optional refilling quotas and per-key rate limits.
- jwt() —
/auth/tokento mint a JWT from a session,/auth/jwksfor the public key set. - email_otp() — passwordless sign-in, email verification, password reset, and (optional) email change via 6-digit OTPs delivered to email. Hashed storage, per-OTP attempt cap, lockout-coupled.
- audit_logs() — best-effort recording of security events into a paginated audit-log collection; event handlers are awaited, without a durable outbox.
- openapi() — Scalar UI at
/auth/reference, OpenAPI 3.1 schema at/auth/openapi.json. - test_utils() — factories, login helpers, OTP capture for tests.
Developer experience
auth.depends.user()/auth.depends.session()FastAPI dependencies with optional variants, bothDepends(...)andAnnotated[...]calling styles documented.- Explicit storage wiring — choose
memory(),mongo(database=...),postgres(url=...), orcustom(adapter=..., backend=...). Fastauth never reads storage settings from the process environment. auth.router+auth.add_middleware(app)— choose route placement explicitly, then install FastAuth's exception handler, CSRF middleware, and security headers.FastAuth.as_asgi()returns a standalone app when you want FastAuth hosted separately.- Typer CLI —
fastauth init --backend memory|mongo|postgres,fastauth migrate,fastauth generate-secret. - mkdocs-material docs + quickstart example app with its own test suite.
Installation
# Core (in-memory adapter only — useful for tests and local dev)
pip install fastauth-py
# MongoDB-backed production
pip install fastauth-py[beanie,jwt]
# Postgres-backed production
pip install fastauth-py[postgres,jwt]
# All implemented optional extras
pip install fastauth-py[beanie,postgres,jwt,cli,docs]
Extras: beanie (MongoDB), postgres (SQLAlchemy async + asyncpg), jwt
(JOSE signing + crypto for at-rest JWK encryption), cli (Typer CLI),
docs (mkdocs-material toolchain).
Python 3.11–3.13 required (>=3.11,<3.14). FastAPI 0.115+, Pydantic 2.11–2.x.
Python 3.14 is not supported in 0.15 because current Beanie 2.x releases exclude it.
Protecting routes
from fastauth import UserView
@app.get("/me")
async def me(user: auth.CurrentUser) -> UserView:
return user
auth.CurrentUser and auth.CurrentSession are bound Annotated dependencies
created with the FastAuth instance. Cookie auth and
Authorization: Bearer … both work transparently.
When postponed annotations are enabled, keep auth as a module-level binding
so FastAPI can resolve auth.CurrentUser. For factory- or closure-scoped auth
instances, use the explicit dependency form:
from fastapi import Depends
@app.get("/me")
async def me(user: UserView = Depends(auth.depends.user())) -> UserView:
return user
Use auth.depends.optional_user() if anonymous requests are allowed.
Configuration
FastAuthOptions is a plain pydantic.BaseModel. Every field has a sensible
default; pass only what you want to override:
from pydantic import SecretStr
from fastauth import FastAuth, FastAuthOptions
from fastauth.database import memory
from fastauth.options import (
AppOptions, CookieOptions, CsrfOptions,
LockoutOptions, RefreshTokenOptions, SecurityHeadersOptions,
)
from fastauth import email_password
options = FastAuthOptions(
secret_key=SecretStr("…"),
database=memory(),
app=AppOptions(name="My App", base_url="https://myapp.com"),
cookie=CookieOptions(secure=True, same_site="strict"),
csrf=CsrfOptions(trusted_origins=("https://myapp.com",)),
lockout=LockoutOptions(max_failures=10, window="5m"),
refresh_token=RefreshTokenOptions(max_age="14d"),
security_headers=SecurityHeadersOptions(
content_security_policy="default-src 'self'",
),
)
auth = FastAuth(options, plugins=[email_password()])
17 sub-configs cover app, session, cookie, password, email,
email_verification, password_reset, email_change, delete_account,
rate_limit, csrf, lockout, refresh_token, security_headers,
production_safety, advanced, plus the top-level database backend. Plugins are behavior
objects passed to FastAuth(..., plugins=[...]).
See docs/concepts/config.md for the full reference.
Documentation
Full docs site: mkdocs serve from a checkout.
- Quickstart
- Config · Sessions · Plugins · Adapters · CSRF · Events · Hooks
- Email verification guide · Password reset guide · User management guide · KMS signing guide
Project layout
fastauth/
├── options.py / exceptions.py # top-level
├── domain/ # pure data: enums, models, events
├── security/ # auth primitives: passwords, tokens, sessions, jwt,
│ # refresh_tokens, lockout, rate_limit
├── storage/ # Core/optional adapter protocols + InMemory/Beanie/Postgres backends
├── messaging/ # email + Jinja2 templates
├── flows/ # sign-up, sign-in, verification, refresh, …
├── plugins/ # email_password, email_otp, api_key, jwt, audit_logs, openapi, test_utils
├── runtime/ # FastAuth, AuthContext, AuthApi, EventBus, hooks
├── web/ # FastAPI integration + CSRF + security headers
└── cli/ # Typer CLI
Status
v0.14.1 — current beta release. Coverage spans unit tests, adapter-contract
tests, integration flows, CLI behavior, and the quickstart example.
pyright --strict is clean. See CHANGELOG.md for the detailed
feature list.
Roadmap:
- OAuth providers (Google → GitHub → Apple → Microsoft)
- 2FA / TOTP
- Webhooks
- HIBP password breach check
- Audit-log enrichment (geo-IP, UA parsing)
Contributing
See CONTRIBUTING.md for the project-wide rules (no leading-underscore names, async-only, Pydantic-everywhere, …). Quick development loop:
uv sync --all-extras
uv run ruff format --check src tests examples docs
uv run ruff check
uv run pyright
uv run pytest
uv run pytest -m "unit and not docker"
uv run mkdocs serve
License
MIT — see LICENSE.
Metadata
Release files for fastauth-py 0.16.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastauth_py-0.16.0.tar.gz | 173.7 kB | With provenance | Details for fastauth_py-0.16.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastauth_py-0.16.0-py3-none-any.whl | Python 3 | none | any | Details for fastauth_py-0.16.0-py3-none-any.whl |
Total release size: 385.7 kB
Release files / fastauth_py-0.16.0.tar.gz
| Download URL | fastauth_py-0.16.0.tar.gz |
|---|---|
| Size | 173.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
84454f98e24f3a169630685e7b59d7da264472d9decadedb1534c0f931dec318
|
|
BLAKE2b-256 checksum How to use checksums |
3ad1071d4a4a40b3803e169c6987a9c42106f1253acf082d859392d136de9698
|
| 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 logRelease files / fastauth_py-0.16.0-py3-none-any.whl
| Download URL | fastauth_py-0.16.0-py3-none-any.whl |
|---|---|
| Size | 212.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7e7428e3593ec8ae6701ac28b3501b35ef0e9496d5260049485a5a3089b3dea3
|
|
BLAKE2b-256 checksum How to use checksums |
cce6ebab5358b5c2605f90c3e4647d7f22d70966fef0232cfa7ec4fa6752d669
|
| 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 logSecurity for fastauth-py 0.16.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.
Attestation for fastauth_py-0.16.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 logA 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.