Skip to main content

Framework-agnostic authentication library for Python

Project description

IronAuth

Bibliothèque d'authentification agnostique du framework pour Python. Cœur sécurisé (Argon2id, JWT en cookies httpOnly, rotation des refresh tokens, CSRF double-submit, blacklist de révocation) et adaptateur FastAPI prêt à monter.

Installation

uv add ironauth          # ou : pip install ironauth
uv add "ironauth[redis]" # stores distribués (blacklist + rate-limit)

Démarrage rapide (FastAPI)

from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI
from ironauth import IronAuth, sqlalchemy_adapter, User

db = sqlalchemy_adapter("sqlite+aiosqlite:///./app.db")

auth = IronAuth(
    database=db,
    config={
        # >= 32 caractères ; à charger depuis l'environnement en production
        "secret_key": "change-me-super-long-secret-key-32-chars-min",
        # En développement local (HTTP), passer secure à False pour que les cookies partent
        "cookie": {"secure": False},
    },
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    await auth.init()  # crée les tables (dev). En prod : migrations Alembic.
    yield


app = FastAPI(lifespan=lifespan)
app.include_router(auth.router)  # expose /auth/*


@app.get("/profile")
async def profile(user: User = Depends(auth.current_user())):
    return {"email": user.email}

Flux côté client

Toutes les mutations exigent un token CSRF : appeler GET /auth/csrf-token, réémettre la valeur reçue dans l'en-tête X-CSRF-Token (le cookie brut est posé automatiquement).

POST /auth/register           {email, password}
POST /auth/login              {email, password}        -> cookies de session
POST /auth/logout
POST /auth/refresh                                     -> rotation des tokens
GET  /auth/me                                          -> utilisateur courant
POST /auth/change-password    {current_password, new_password}

Le mot de passe doit faire au moins 12 caractères avec majuscule, minuscule, chiffre et caractère spécial.

Plugins (optionnels)

from ironauth import (
    IronAuth, sqlalchemy_adapter,
    oauth, two_factor, rate_limit, smtp, resend,
)

auth = IronAuth(
    database=sqlalchemy_adapter("postgresql+asyncpg://.../app"),
    config={
        "secret_key": "...",
        "require_verified_email": True,       # bloque le login tant que non vérifié
        "trust_proxy": True,                  # lit X-Forwarded-For derrière un proxy fiable
        "oauth": {
            "google": {
                "client_id": "...",
                "client_secret": "...",
                "redirect_uri": "https://app.example.com/auth/oauth/google/callback",
            },
        },
        "email": {"base_url": "https://app.example.com", "app_name": "MonApp"},
    },
    plugins=[
        oauth(["google"]),
        two_factor(),
        rate_limit(max_attempts=5, window=300, block_duration=900),
        resend(api_key="re_..."),             # ou smtp(host=..., port=587, ...)
    ],
)

Routes ajoutées selon les plugins actifs :

GET  /auth/oauth/{provider}                 (google | github)
GET  /auth/oauth/{provider}/callback
POST /auth/2fa/enable                        -> secret + QR code base64
POST /auth/2fa/confirm      {code}
POST /auth/2fa/validate     {two_factor_token, code}   # après un login avec 2FA
POST /auth/2fa/disable      {code}
POST /auth/send-verification-email
POST /auth/verify-email     {token}
POST /auth/forgot-password  {email}
POST /auth/reset-password   {token, password}

Avec la 2FA activée, POST /auth/login renvoie {two_factor_required: true, two_factor_token} au lieu d'une session : échanger ce token (usage unique, 5 min) sur /auth/2fa/validate avec le code TOTP pour obtenir la session.

Sécurité

Mots de passe hashés en Argon2id (rehash transparent). Tokens de vérification et de reset stockés hashés en SHA-256 avec expiration. Un changement ou une réinitialisation de mot de passe invalide toutes les sessions existantes. logout révoque immédiatement les tokens access et refresh via la blacklist.

En production : servir en HTTPS (cookies secure par défaut), charger secret_key depuis l'environnement, utiliser Redis (redis_url) pour la blacklist et le rate-limit sur plusieurs workers, et gérer le schéma avec Alembic plutôt que auth.init().

Développement

uv sync
uv run pytest

Licence

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ironauth-0.2.2.tar.gz (30.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ironauth-0.2.2-py3-none-any.whl (27.9 kB view details)

Uploaded Python 3

File details

Details for the file ironauth-0.2.2.tar.gz.

File metadata

  • Download URL: ironauth-0.2.2.tar.gz
  • Upload date:
  • Size: 30.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for ironauth-0.2.2.tar.gz
Algorithm Hash digest
SHA256 85b975458d981fb5991ddfabf492742d7257e39a535376667135ba30fbb5b895
MD5 4f02dfc2989b131444fa882b9f014b56
BLAKE2b-256 3b62cd723f7913d375afb42539cdb746700391be20f60a1eb5d99d0ed93c0c64

See more details on using hashes here.

File details

Details for the file ironauth-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: ironauth-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 27.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for ironauth-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ff0334702a022eca159965360f6c478c18c04d2ad9e9da32d354b968f46562f2
MD5 80bab222dd8e41af252751ba884dad69
BLAKE2b-256 576cc5bd8f958a81bfa9110025e029cecce01be1fcc0c0df7e8fc23ea484146d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page