Skip to main content

A flexible and secure authentication library for FastAPI.

Project description

FastAPI MyAuth

PyPI version Python Version License: MIT Ruff codecov

A flexible and secure authentication library for FastAPI, designed to integrate seamlessly with your existing SQLModel ORM. FastAPI MyAuth provides robust features including:

  • User Management: CRUD operations for users, including activation/deactivation.
  • Authentication Methods:
    • Traditional email/password login.
    • Magic link based login for a passwordless experience.
    • WebAuthn passkey registration and usernameless login.
    • OAuth 2.0/OpenID Connect social login.
    • Refresh token mechanism for extended sessions without re-authenticating.
  • Security Features:
    • Password hashing with Argon2.
    • JSON Web Token (JWT) based authentication.
    • Two-Factor Authentication (TOTP) support.
    • Password recovery flows.
    • Email validation: Optional mandatory email confirmation for new user registrations to ensure valid email addresses.
    • Rate limiting: Optional application-wide limits with authenticated and unauthenticated defaults, per-route overrides, Redis support, and trusted-proxy client IP handling.
  • Email Integration: Templates and functions for sending various authentication-related emails (e.g., password reset, magic links, email confirmation).
  • Role-Based Access Control (RBAC): Easily add roles to users and protect endpoints based on these roles.
  • Extensible: Designed with generics to allow customization of the User model and integration with existing database sessions.

🚀 Getting Started

To quickly integrate FastAPI MyAuth into your FastAPI application, install it via pip:

pip install fastapi_myauth

Then, you can typically set up the authentication router in your FastAPI application like this:

from fastapi import FastAPI
from sqlmodel import Session, create_engine, SQLModel

from fastapi_myauth import auth, models
from fastapi_myauth.auth import FastAuth
from fastapi_myauth.config import Settings

app = FastAPI()

# Your database engine setup (example for SQLite)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

# Initialize FastAuth with your custom User model (or use default)
# You can extend models.User, models.UserCreate, models.UserRead, models.UserUpdate
# to add custom fields. For example, if you want a `language` field:
class MyUser(models.User, table=True): # Important: table=True on your concrete user model
    language: str = "en"

class MyUserRead(models.UserRead):
    language: str

class MyUserCreate(models.UserCreate):
    language: str | None = None

class MyUserUpdate(models.UserUpdate):
    language: str | None = None


config = Settings(
    SECRET_KEY="replace-with-a-stable-random-secret",
    TOTP_SECRET_KEY="replace-with-a-valid-fernet-key",
)
components = auth.AuthComponents(
    user_model=MyUser,
    user_read=MyUserRead,
    user_create=MyUserCreate,
    user_update=MyUserUpdate,
)
fast_auth = FastAuth(engine=engine, components=components, config=config)

# Call this once your app starts, e.g., in a startup event or directly
create_db_and_tables()

# Include the authentication router
app.include_router(fast_auth.get_router())

@app.on_event("startup")
def on_startup():
    # Initialize the first superuser if not exists
    with Session(engine) as session:
        crud_user = fast_auth.crud_user()
        user = crud_user.get_by_email(session, email=config.FIRST_SUPERUSER)
        if not user:
            user_in = MyUserCreate(
                email=config.FIRST_SUPERUSER,
                password=config.FIRST_SUPERUSER_PASSWORD,
                is_superuser=True,
                language="en" # Set default for custom field
            )
            crud_user.create(session, obj_in=user_in)

# Example protected endpoint
from fastapi import Depends
from fastapi_myauth.api.deps import APIDependencies

# Get dependency instance from your fast_auth object
deps_instance = fast_auth.deps()

@app.get("/protected-route")
def read_protected_route(
    current_user: MyUserRead = Depends(deps_instance.get_current_active_user)
):
    return {"message": f"Hello, {current_user.email}! This is a protected route."}

For more detailed usage instructions, configuration options, and advanced customization, please refer to the Usage Documentation.

🌳 Project Structure

fastapi_myauth/
├── api/                  # FastAPI routers and dependencies for REST API endpoints
│   ├── v1/               # Versioned API endpoints (e.g., login, users)
│   └── deps.py           # FastAPI dependency injection for auth components
├── crud/                 # CRUD operations for database models
│   ├── base.py           # Generic CRUD base class
│   ├── crud_token.py     # CRUD for refresh tokens
│   └── crud_user.py      # CRUD for user operations
├── email/                # Email sending utilities and templates
├── models/               # Pydantic/SQLModel definitions for data structures
├── security.py           # Password hashing, JWT handling, TOTP
├── config.py             # Application settings
├── auth.py               # Main FastAuth class for setup and router inclusion
└── test_main.py          # Example FastAPI app for testing and demonstration

📚 Documentation

Detailed documentation is available in the docs directory:

  • Usage Documentation: Learn how to install, configure, and use the fastapi_myauth library in your projects.
  • Passkeys: Configure backend WebAuthn registration, login, and credential management.
  • Rate Limiting: Protect package and application routes, including Redis and Cloudflare/Traefik deployments.
  • Development & Contributing: Information for developers interested in contributing to the project, including setup instructions and coding standards.

✨ Features at a Glance

  • FastAPI Integration: Designed exclusively for FastAPI.
  • SQLModel Native: Works seamlessly with SQLModel for ORM operations.
  • Secure Authentication: Built with modern security practices (Argon2 for passwords, JWTs).
  • Email Management: Integrated email sending for common auth flows.
  • Customizable User Model: Easily extendable User model to fit specific application needs.
  • Dependency Injection: Leverages FastAPI's dependency injection system for robust and testable code.

🤝 Contributing

Contributions are welcome! Please see our Contributing Guide for details on how to get started.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

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

fastapi_myauth-1.5.2.tar.gz (169.9 kB view details)

Uploaded Source

Built Distribution

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

fastapi_myauth-1.5.2-py3-none-any.whl (57.8 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_myauth-1.5.2.tar.gz.

File metadata

  • Download URL: fastapi_myauth-1.5.2.tar.gz
  • Upload date:
  • Size: 169.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fastapi_myauth-1.5.2.tar.gz
Algorithm Hash digest
SHA256 323420adb0f38c2376111ee09f557bab3e4da9deb9401faef109ad88141abd94
MD5 e0d62ec255b3f0a21de4578fabdaa103
BLAKE2b-256 57e84d563766c52c70414a1165b3d26b01de666e84ed0d528e400153456ada23

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_myauth-1.5.2.tar.gz:

Publisher: cd.yml on zonistefano/fastapi_auth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_myauth-1.5.2-py3-none-any.whl.

File metadata

  • Download URL: fastapi_myauth-1.5.2-py3-none-any.whl
  • Upload date:
  • Size: 57.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fastapi_myauth-1.5.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0f44f5be272ee3e9ec56fbbc101e1585c7c026e0d982c9b219cba44f4f714245
MD5 abb734f109af65742ec2a3fe3a5d4ccd
BLAKE2b-256 7de811e2bcb30ff5f9cbe5277570ef3d75d38497fd9ae46698b86579b23d89ce

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_myauth-1.5.2-py3-none-any.whl:

Publisher: cd.yml on zonistefano/fastapi_auth

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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