Skip to main content

FastAPI-compatible authentication, OAuth, CSRF, and session management.

Project description

authshield

A modular, framework-agnostic security suite providing FastAPI-compatible Authentication, CSRF Protection, and Session Management.

authshield uses a dynamic factory architecture, allowing it to seamlessly inject secure, chainable configuration methods directly into FastAPI or any custom subclass wrapper you are already using -- without breaking your existing inheritance tree or IDE autocomplete.


Features

  • Zero-Dependency-Inversion: Extends your application class dynamically at runtime.
  • Fluent & Chainable API: Configure your entire security stack in a single, elegant block.
  • Fully Modular: Core engines (Auth, CSRF, Sessions) are separated internally for clean maintainability.
  • Type Safe: Built from the ground up to support PEP 561 standard inline type hints.

Installation

Install authshield via uv (or your preferred package manager):

uv add authshield

Quick Start

authshield provides a shield_class factory that wraps your application class (e.g., FastAPI) and injects fluent configuration methods like .useAuth() and .useCSRF().

from fastapi import FastAPI
from authshield import shield_class

# 1. Dynamically wrap your base application class
ShieldedApp = shield_class(FastAPI)

# 2. Instantiate and chain your security configuration seamlessly
app = (
    ShieldedApp(title="My Shielded API")
    .useAuth(config={...})
    .useCSRF(config={...})
)

@app.get("/")
async def root():
    return {"status": "shielded"}

Architecture

Module Overview

authshield/
├── config.py           # CsrfConfig, AuthConfig, SsoConfig (Pydantic models)
├── extended.py         # shield_class() factory
├── auth/
│   ├── models.py       # UserSession, UserEntry, UserUpdate
│   ├── _auth_handler.py    # Password + SSO authentication logic
│   ├── _hashing.py         # Argon2id password hashing
│   ├── _require_auth.py    # FastAPI dependency for route protection
│   └── _use_auth.py        # Wires AuthConfig into app state
├── csrf/
│   ├── _csrf_handler.py    # CSRFMiddleware (Double-Submit Cookie)
│   └── _use_csrf.py        # Registers CSRF middleware
├── oauth/              # (planned)
└── session/            # (planned)

Authentication

Two authentication flows are supported:

Flow Entry point Description
Password authenticate_user(email, password, config) Verifies credentials via Argon2id hash and returns a UserSession.
SSO authenticate_user_by_sso(claims, config) Matches SSO claims to local users (by sub or email), with optional auto-merging and auto-provisioning.

Route-level protection uses the require_auth FastAPI dependency:

from fastapi import Depends
from authshield.auth import require_auth

@app.get("/me")
async def me(user=Depends(require_auth())):
    return user

@app.get("/admin")
async def admin(user=Depends(require_auth("admin", "superadmin"))):
    return user

CSRF Protection

CSRFMiddleware implements the Double-Submit Cookie pattern with optional HMAC-signed token binding. Configure via CsrfConfig:

from authshield.config import CsrfConfig

config = CsrfConfig(
    trusted_origins=["api.example.com", "app.example.com"],
    cookie_samesite="Strict",
    signed_mode=True,
    secret_key="your-secret-key",
)

Configuration Models

Model Purpose
CsrfConfig Cookie name, header, SameSite, trusted origins, signed mode
AuthConfig SSO toggle, session cookie name, session resolver, user lookup
SsoConfig SSO callbacks, auto-merging/provisioning, role mapping

Advanced Architecture

Stacking Custom Classes

Because authshield uses dynamic typing instead of a rigid subclass hierarchy, it plays nicely if you are already using a custom framework wrapper:

class MyEnterpriseApp(FastAPI):
    def company_telemetry(self):
        pass

# authshield blends perfectly into your custom pipeline
SecuredApp = shield_class(MyEnterpriseApp)

app = SecuredApp()
app.company_telemetry()  # Stays intact!
app.useAuth(...)         # Injected smoothly!

Roadmap / Coming Soon

  • Server-side and Encrypted Client-side Session Management
  • OAuth2 support for OAuth2.0 and OpenID Connect

License

This project is licensed under the MIT License.

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

authshield-0.1.2.tar.gz (17.6 kB view details)

Uploaded Source

Built Distribution

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

authshield-0.1.2-py3-none-any.whl (25.7 kB view details)

Uploaded Python 3

File details

Details for the file authshield-0.1.2.tar.gz.

File metadata

  • Download URL: authshield-0.1.2.tar.gz
  • Upload date:
  • Size: 17.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for authshield-0.1.2.tar.gz
Algorithm Hash digest
SHA256 f946bc3f3b24e81b35a57d880b1bb4fda463f3f3e5ec519f5464019362fbb05a
MD5 fbbc54e23c8eed2648280f7ea4180c5e
BLAKE2b-256 bf703c687bf07b7fd09f8ea6a7e346697bb8afecda7a1f1e3cfa77faa98672e9

See more details on using hashes here.

File details

Details for the file authshield-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: authshield-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 25.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for authshield-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f44578991318c8b2775d6bd7c54e0799dd093c441ad0163962107dae6634638e
MD5 2ea24033d178ee3cf8b398351a0abc3f
BLAKE2b-256 c4af3784ee5e970f6aab23c8c4fceef609c7df88ab5034947f58a76d286174b9

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