Skip to main content

Simple login/password authentication module for FastAPI project.

Project description

FastAPI Lite Auth

This is a login/password authentication module that can be quickly and easily integrated into your project. JWT token is used as the authentication method. It is recommended to use the module in small projects and pet projects.

To add the module to your project, you need to:

  1. Install the module
  2. Override the get_user method in auth_manager
  3. Override the user schema and model in auth_manager if they differ from yours
  4. Specify which fields in the user model represent the login and password

More detailed installation and configuration instructions can be found in the Installation section.

Based on AuthX


Installation

1. Installing the module

Install module pip install fastapi-lite-auth The module is currently being prepared for publishing to PyPI.

2. Module integration

In the folder containing your API routers (usually routers/), create a file named auth.py. Import the necessary components and create the API router: auth.py:

from fastapi import APIRouter
from fastapi_lite_auth import auth_config, auth_router, auth_manager

auth_config.authx_ready()

router = APIRouter()
router.include_router(
    router=auth_router
)

The auth_config.authx_ready() function configures the AuthX object. You should call it after modifying any auth_config settings.

3. Basic module configuration

To make the module work, you need to do a few things:

3.1. Override the user model and schema.

The model is an ORM-oriented class. The schema is a class that describes the data the API will return.

By default, they look like this:

from pydantic import BaseModel

class BasicGetUserSchema(BaseModel):
    id: int
    name: str
    username: str
    email: str
    
class BasicUserModel:
    id: int
    name: str
    email: str
    username: str
    password: str

Example of overriding the user model and schema:

from pydantic import BaseModel
from fastapi_lite_auth import auth_config


class CustomGetUserSchema(BaseModel):
    id: int
    full_name: str
    phone: str
    username: str
    email: str
    passport_number: str
    insurance_number: str


class CustomUserModel:
    id: int
    full_name: str
    phone: str
    username: str
    email: str
    passport_number: str
    insurance_number: str
    password: str


auth_config.models_config.UserModel = CustomUserModel
auth_config.schemas_config.GetUserSchema = CustomGetUserSchema

3.2. Define the user retrieval method.

This is a function that should find a user record in your database using the field used as login. Requirements:

  • The function must accept a login argument of type str
  • It must return an instance of the user model described above or None if not found

Example override:

import sqlite3
from fastapi_lite_auth import auth_config, auth_manager


def get_user_by_login(login: str | None = None) -> auth_config.models_config.UserModel | None:
    conn = sqlite3.connect("./db.db")
    select = conn.execute(f"SELECT * FROM user WHERE email = ?", (login,))
    res = select.fetchone()

    if res is None:
        return None

    user_model = auth_config.models_config.UserModel()
    user_model.id = res[0]
    user_model.full_name = res[1]
    user_model.username = res[2]
    user_model.email = res[3]
    user_model.password = res[4]

    return user_model


auth_manager.get_user = get_user_by_login

3.3. Configure login and password fields

By default, username and password fields are used. Example configuration:

from fastapi_lite_auth import auth_config

auth_config.login_config.login_field_name = "email"
auth_config.login_config.password_field_name = "password"
auth_config.authx_ready()

3.4. Retrieving the Current User

The authentication token is stored in a cookie. When making a request to the server, it must be sent in the Credentials HTTP header. To retrieve the user from the JWT token, you need to specify a dependency in the route function:

from fastapi import APIRouter, Depends
from fastapi_lite_auth import current_user

router = APIRouter()

@router.get(path="/me")
async def get_user(user = Depends(current_user)):
    return {"user": user}

The current_user dependency returns an instance of the GetUserSchema class-schema with the authenticated user's data, which is configured in section 3.1. How it works:

  1. The application retrieves the JWT token from the Credentials header
  2. The user's login is extracted from the token
  3. The user is fetched by this login using the get_user function, which is configured in section 3.2.

4. Additional configuration

4.1. Define a password hashing function (if passwords are stored hashed in your DB)

This function is used to hash the incoming password for comparison. Requirements:

  • Must accept a data argument of type str
  • Must return a str hash

Example:

from hashlib import sha256
from fastapi_lite_auth import auth_manager


def hash(data: str) -> str:
    return sha256(data.encode()).hexdigest()


auth_manager.hash = hash

4.2. Configure the secret key

The secret key is used to sign the JWT token. It should be stored in environment variables. By default, it’s generated from the current datetime.

Example override:

import os
from fastapi_lite_auth import auth_config

auth_config.token_config.secret_key = os.getenv("AUTH_SECRET")
auth_config.authx_ready()

4.3. Configure cookie parameters

Here’s how to configure cookies and their default values:

from fastapi_lite_auth import auth_config

auth_config.cookie_config.cookie_name = "auth_token"
auth_config.cookie_config.cookie_httponly = False
auth_config.cookie_config.cookie_secure = False
auth_config.cookie_config.cookie_samesite = "lax"
auth_config.cookie_config.cookie_max_age = 3600
auth_config.cookie_config.cookie_path = "/"
auth_config.cookie_config.cookie_domain = None
auth_config.cookie_config.cookie_expires = None
auth_config.authx_ready()

Example integration

You can check out the example app in the example directory. Its configuration is described in example/api/routers/auth.py.

Requirements

pip install -r requirements.txt

or

pip install "fastapi[standard]"
pip install authx 

Start Example

python -m example.api.main

or

python3 -m example.api.main

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_lite_auth-1.0.1.tar.gz (8.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_lite_auth-1.0.1-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_lite_auth-1.0.1.tar.gz.

File metadata

  • Download URL: fastapi_lite_auth-1.0.1.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for fastapi_lite_auth-1.0.1.tar.gz
Algorithm Hash digest
SHA256 0bcdad7273595c7f2ebac58b4a23e3cbd30eb68ae68eb80b57b76b8d01a206ae
MD5 4d2902e8c34c4ad911b9d9156500de3b
BLAKE2b-256 819545611fed372ba898b6bb344519588e2594219845c89fbf66ba531c83eabd

See more details on using hashes here.

File details

Details for the file fastapi_lite_auth-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_lite_auth-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ba32feab3c274497821f04340d7912e063936088b495194e62966a9d4ba1bc8a
MD5 3cc99a74002bab63abc6d94bd760fc4a
BLAKE2b-256 5a682c55acf963f18bdda4f8615de7e9d74d5f8da253f10afb14b853e5576871

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