Skip to main content

A comprehensive FastAPI authentication library that provides a robust and integrated set of features for user authentication, registration, and account management. This library also supports third-party social account authentication, making it easy to integrate with popular social platforms.

Project description

FastAPI Auth Toolkit [Beanie]

The FastAPI Auth Toolkit [Beanie] provides a comprehensive authentication solution for FastAPI applications. It offers robust features for user authentication, registration, and account management, and supports integration with popular third-party social authentication platforms.

Features

  • User Authentication and Registration: Securely manage user accounts with built-in authentication and registration capabilities.
  • Account Management: Easily handle user profiles and account details.
  • Third-Party Social Authentication: Integrate with major social platforms for seamless social login functionality.
  • Simple Configuration: Effortlessly configure and set up with straightforward integration steps.

Installation

You can install the fastapi-auth-toolkit[beanie] package using either pip or pipenv.

Using pip

To install the package with pip, execute:

pip install fastapi-auth-toolkit[beanie]

Project Configuration

  • In your FastAPI application, typically located in main.py or another startup file, integrate the authentication routes and load the configuration as follows:

1. Setup database connection and collection - db.py

  • The first thing to do is to create a MongoDB connection using mongodb/motor (automatically installed with Beanie).
from motor.motor_asyncio import AsyncIOMotorClient

# Database configuration
DATABASE_URL = "mongodb://localhost:27017"
database_name = "database_name"

# Create a MongoDB client and get the database instance
database_client = AsyncIOMotorClient(
    DATABASE_URL, uuidRepresentation="standard"
)
database = database_client.get_database(database_name)

2. Initialize Beanie - db.py

  • When initializing your FastAPI app, it's important that you initialize Beanie so it can discover your models. We can achieve this using Lifespan Events on the FastAPI app
from typing import List, Type
from beanie import init_beanie, Document

# Document model registry
document_models_registry: List[Type[Document]] = []

async def init_database():
    try:
        # Initialize Beanie with the provided document models and database
        await init_beanie(
            database=database,
            document_models=document_models_registry
        )
        print("Beanie initialized successfully.")
    except Exception as e:
        print(f"Error initializing Beanie: {e}")
        raise

3. Configuration - main.py

from fastapi import FastAPI
from contextlib import asynccontextmanager

from fastapi_auth_toolkit import FastapiAuthToolkitConfig
from db import document_models_registry, init_database


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Asynchronous context manager to handle application lifespan events.

    :param app: The FastAPI application instance.
    """

    # Initialize FastAPI Auth Toolkit
    FastapiAuthToolkitConfig(
        app=app,
        document_models=document_models_registry,
    )

    # Initialize beanie document
    await init_database()

    # Yield control back to the FastAPI app
    yield

# Create your FastAPI app
app = FastAPI(lifespan=lifespan)

Authentication Method - jwt, session, or cookies

1. session based auth.

from fastapi_auth_toolkit import FastapiAuthToolkitConfig

FastapiAuthToolkitConfig(
    auth_method="session",
)

2. cookies based auth.

from fastapi_auth_toolkit import FastapiAuthToolkitConfig

FastapiAuthToolkitConfig(
    auth_method="cookies",
)

3. jwt based auth - fully customized.

  • Initialize FastAPI Auth Toolkit with optional custom JWT settings
from datetime import timedelta
from fastapi_auth_toolkit import FastapiAuthToolkitConfig

FastapiAuthToolkitConfig(
    auth_method="jwt",
    jwt_settings={
        "access_token_lifetime": timedelta(minutes=5),  # Example JWT settings
        "refresh_token_lifetime": timedelta(days=1),
        "update_last_login": False,
        "algorithm": "HS256",
        "auth_header_types": "Bearer",
        "auth_header_name": "HTTP_AUTHORIZATION",
        "user_id_field": "user_id"
    },
)

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_auth_toolkit-0.0.2.tar.gz (26.9 kB view details)

Uploaded Source

Built Distribution

fastapi_auth_toolkit-0.0.2-py3-none-any.whl (41.6 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_auth_toolkit-0.0.2.tar.gz.

File metadata

  • Download URL: fastapi_auth_toolkit-0.0.2.tar.gz
  • Upload date:
  • Size: 26.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.4

File hashes

Hashes for fastapi_auth_toolkit-0.0.2.tar.gz
Algorithm Hash digest
SHA256 88748a34d29acf67f1d4d0f8df4b17372317da1580308d3dff66f62d7c041cf9
MD5 fe6e5a41bd458113b4f30db2fe0dcbd5
BLAKE2b-256 91d2070b78d71c607e20f77d1b33b4a309e7985a319ed5d68e2786ab2066d696

See more details on using hashes here.

File details

Details for the file fastapi_auth_toolkit-0.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_auth_toolkit-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 631ffdde4236504c92aa6aa19b451fa2b9a2cec07df86dadb70991a916a5b9e6
MD5 1ccda6799ee2455f5f0d859caaed0e48
BLAKE2b-256 aa0cf5f1317b8c05e1ac45e9ae9ae2eb7f94884240760aa0a8bb0560b17c01f5

See more details on using hashes here.

Supported by

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