Skip to main content

A lightweight JWT authentication library for FastAPI and SQLAlchemy.

Project description

fastapi-lightauth

A lightweight JWT authentication library for FastAPI and SQLAlchemy. Built with simplicity in mind for small and medium FastAPI projects.

Features:

  • JWT authentication
  • Secure password hashing with bcrypt
  • User registration and login endpoints
  • Current-user dependency injection
  • Extendable SQLAlchemy user models
  • Extendable Pydantic schemas
  • Async SQLAlchemy support

Installation

pip install fastapi-lightauth

Quick start

1. Define your user model

LightAuth requires 'UserMixin', but everything else is completely up to you

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from lightauth import UserMixin


class Base(DeclarativeBase):
  pass


class User(UserMixin, Base):
  __tablename__ = "users"

  extra_stuff: Mapped[str] = mapped_column(default="no extra stuff here")

2. Optional: extend your response schema

You can add fields that you want returned in API responses:

from lightauth.schemas import UserReadBase


class UserReadSchema(UserReadBase):
  extra_stuff: str

3. Create a session dependency

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from typing import AsyncGenerator, Any

engine = create_async_engine("sqlite+aiosqlite:///:memory:")
session_maker = async_sessionmaker(engine)


async def get_session() -> AsyncGenerator[AsyncSession, Any]:
    async with session_maker() as session:
        yield session

4. Set up LightAuth

from lightauth import LightAuth

auth = LightAuth[User](
  secret="your-secret-key",
  model=User,
  get_session=get_session,
)

Optionally configure token lifespan via token_lifespan_days


5. Add the router

from lightauth import get_auth_router
from lightauth.schemas import UserCreateBase

app.include_router(
  get_auth_router(
    auth,
    UserReadSchema,
    UserCreateBase,
  )
)

Using authentication in routes

You protect routes using a FastAPI dependency:

from fastapi import Depends

@app.get("/hello")
async def hello(user: User = Depends(auth.current_user)):
    return f"Hello, {user.username}"

That dependency will:

  • read the Bearer token
  • validate the JWT
  • load the user from the database
  • inject the full SQLAlchemy user object

Endpoints

Register

POST /auth/register
{
  "username": "...",
  "password": "..."
}

Returns the created user.


Login

POST /auth/login
{
  "username": "...",
  "password": "..."
}

Returns:

{
  "access_token": "eyJ...",
  "token_type": "Bearer"
}

Current user

GET /auth/me

Requires:

Authorization: Bearer <token>

Returns the current user.


Security notes

  • Passwords are hashed using bcrypt
  • JWT tokens include:
    • sub → user ID
    • exp → expiration timestamp
  • Default token lifetime: 30 days

License

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

fastapi_lightauth-0.1.0.tar.gz (6.1 kB view details)

Uploaded Source

Built Distribution

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

fastapi_lightauth-0.1.0-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_lightauth-0.1.0.tar.gz.

File metadata

  • Download URL: fastapi_lightauth-0.1.0.tar.gz
  • Upload date:
  • Size: 6.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for fastapi_lightauth-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0a83a3eb4856e87a8d40ec405a0b0162fcf850c6651eeec41dfd7f44dfdbc19e
MD5 60c304a9503e39290b2e679a3f971500
BLAKE2b-256 b41d1c06e1834a435a2ba5c584f4b3f326017323b479adc3d1f52f2759432dcc

See more details on using hashes here.

File details

Details for the file fastapi_lightauth-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_lightauth-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 37bcd6e0f87b701f39ecc1fae9c4a97f392002fb0beeff7c8ee2fe9de5a006d9
MD5 89aeb8c9158c26b5cd9c36f89087d755
BLAKE2b-256 c90bb3fc48f9711a0f7ac828085b30c503395ade29f88f2a5f6a1db28f7ce2ac

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