Production-ready FastAPI authentication & security library
Project description
AuthForge
Production-grade, multi-tenant authentication and authorization for Python.
Why AuthForge?
Every B2B Python project needs auth. Building it from scratch is:
- Time consuming (weeks of work)
- Easy to get wrong (security mistakes are costly)
- Repetitive (everyone solves the same problems)
AuthForge gives you enterprise-grade auth in minutes, not weeks.
pip install authforge
from authforge import Auth
auth = Auth(
db_url="postgresql+asyncpg://...",
jwt_secret="your-secret",
multi_tenant=True,
)
app.include_router(auth.get_router(), prefix="/auth")
@app.get("/leads")
async def get_leads(user=auth.protect("leads:read")):
return {"tenant": user.tenant_id}
That's it. Full auth system running.
Features
- Multi-tenancy first — tenant isolation enforced at library level
- JWT auth — access + refresh tokens with automatic rotation
- RBAC — 6 built-in roles with granular permissions
- MFA — TOTP-based (Google Authenticator / Authy)
- Email Verification — compulsory verification flow for new users
- Device Fingerprinting — identify and manage trusted devices
- Anomaly Detection — impossible travel, new device alerts, unusual hour detection
- Step-Up Auth — contextual multi-factor re-verification for sensitive actions
- Invite system — employees are invited, not self-registered
- Breach detection — HaveIBeenPwned check on every password
- Audit logs — every action logged automatically with anomaly flags
- Flexible config — code, YAML, or environment variables
- Custom email — plug in SendGrid, SES, or any provider
- Hardened Defaults — CSP/HSTS headers, rate limiting, and encryption-at-rest
🔒 Security Hardening
AuthForge is built with a security-first philosophy. When you use auth.register_security_middleware(app), the following protections are automatically enabled:
- Encryption-at-Rest: Sensitive database fields (MFA secrets, user payloads) are encrypted using AES-256 (Fernet).
- Security Headers: Automatic injection of
Content-Security-Policy,Strict-Transport-Security,X-Frame-Options, andX-Content-Type-Options. - Rate Limiting: Built-in sliding window protection (100 req/min) for all authentication endpoints.
- Timing Attack Protection: Constant-time string comparisons for all secrets and tokens.
Verifying Security
You can verify these features on your local machine by running:
python examples/verify_security.py
Installation
pip install authforge
Quick Start
from fastapi import FastAPI
from authforge import Auth
app = FastAPI()
auth = Auth(db_url="...", jwt_secret="...")
@app.on_event("startup")
async def startup():
await auth.init_db()
app.include_router(auth.get_router(), prefix="/auth")
Configuration
AuthForge supports three config styles. ENV variables take highest priority.
Code:
auth = Auth(db_url="...", jwt_secret="...")
YAML (authforge.yaml):
jwt:
secret: "your-secret"
database:
url: "postgresql+asyncpg://..."
Environment variables:
AUTHFORGE_JWT_SECRET=your-secret
AUTHFORGE_DB_URL=postgresql+asyncpg://...
Documentation
Full docs at authforge.readthedocs.io
Administrative API
AuthForge provides built-in management endpoints for tenant and user administration (enforced via RBAC):
GET /auth/admin/users— List all users in the current tenant.PATCH /auth/admin/users/{id}/role— Promote/demote users (respects hierarchy).PATCH /auth/admin/tenants/{id}/status— Superadmin control for suspending/activating tenants.
Security Configuration & Deep Dive
AuthForge provides several production-grade security layers. Here is a quick breakdown of What they are, Why they are used, and if they can be Customized:
🕵️ 1. Anomaly Detection (Risk Scoring)
- What: Monitors login behavior (IP, Country, Time) and assigns a 0-100 risk score.
- Why: Stops attackers from using stolen credentials if their behavior looks "weird."
- Customization: Enable/Disable via
security.anomaly_detection_enabled. Custom rules can be injected via theAuthconstructor.
🔐 2. Step-Up Authentication
- What: Forces re-authentication before sensitive actions (e.g., deleting data).
- Why: Prevents "Unlocked Laptop" attacks where an active session is left unattended.
- Customization: Use the
@auth.step_up_required(valid_window_minutes=15)decorator to set your own security windows.
🔨 3. Brute-Force Protection
- What: Automatically locks accounts or destroys tokens after multiple failed attempts.
- Why: Stops automated bots from guessing your users' passwords or recovery links.
- Customization: Change limits via
security.max_login_attempts(Default: 5).
💻 4. Device Fingerprinting
- What: Identifies a browser and hardware configuration beyond just cookies.
- Why: Backbone of identity trust; allows users to "Trust" their primary devices.
- Customization: Complete audit logs available in
device_fingerprintsdatabase table.
License
MIT © AuthForge Maintainers
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 authforge-0.1.0.tar.gz.
File metadata
- Download URL: authforge-0.1.0.tar.gz
- Upload date:
- Size: 61.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e5cc2fbe03900b946117f9e5fe9870be6969ac223c6daf2ab69d43bfe4c0e3e5
|
|
| MD5 |
cdbb85fc55b09ba6b9b05763688090a5
|
|
| BLAKE2b-256 |
50b3ab90533b72297f906f2c5b8a1f2bbdd3ef340782051e06f1fd272a8019f7
|
File details
Details for the file authforge-0.1.0-py3-none-any.whl.
File metadata
- Download URL: authforge-0.1.0-py3-none-any.whl
- Upload date:
- Size: 56.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c16df4932c209654486233021bfe04b44d73db1933d977f10894bfa19ff67b33
|
|
| MD5 |
661b47f87b1bd1c991e96728892746b1
|
|
| BLAKE2b-256 |
3f32ed3d42c361243c88f36bb767083059e0ea74c6ef00a4f10bd98a9a498a7e
|