Skip to main content

AuthForge

Production-grade, multi-tenant authentication and authorization for Python.

License: MIT Python 3.10+ FastAPI


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, and X-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 the Auth constructor.

🔐 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_fingerprints database table.

License

MIT © AuthForge Maintainers

Metadata

Release files for authforge 0.1.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 authforge 0.1.0
File Size Uploaded Provenance
authforge-0.1.0.tar.gz 61.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for authforge 0.1.0
File Interpreter ABI Platform
authforge-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 118.0 kB

Release files / authforge-0.1.0.tar.gz

Download URL authforge-0.1.0.tar.gz
Size 61.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e5cc2fbe03900b946117f9e5fe9870be6969ac223c6daf2ab69d43bfe4c0e3e5
BLAKE2b-256 checksum
How to use checksums
50b3ab90533b72297f906f2c5b8a1f2bbdd3ef340782051e06f1fd272a8019f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Release files / authforge-0.1.0-py3-none-any.whl

Download URL authforge-0.1.0-py3-none-any.whl
Size 56.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c16df4932c209654486233021bfe04b44d73db1933d977f10894bfa19ff67b33
BLAKE2b-256 checksum
How to use checksums
3f32ed3d42c361243c88f36bb767083059e0ea74c6ef00a4f10bd98a9a498a7e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Security for authforge 0.1.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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