Skip to main content

Litestar Auth

Project description

litestar-auth

litestar-auth is a production-focused authentication and authorization library for Litestar. It gives Litestar apps a native plugin for registration, login, email verification, password reset, route guards, and optional OAuth, Redis-backed features, and TOTP without forcing you to rebuild security-critical flows from scratch.

Tests Coverage Downloads PyPI Python versions License Docs

Documentation: https://zylvext.github.io/litestar-auth/

Quick peek

This is the same app.py used in the Quickstart. The quickstart page adds the SQLite table bootstrap and the register/verify/login request flow. To run this exact SQLite demo locally, install aiosqlite alongside litestar-auth.

"""Minimal Litestar auth quickstart app mirrored in docs/quickstart.md."""

from __future__ import annotations

import os
from datetime import timedelta
from typing import Any
from uuid import UUID

from litestar import Litestar, Request, get
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from litestar_auth import (
    AuthenticationBackend,
    BaseUserManager,
    BearerTransport,
    LitestarAuth,
    LitestarAuthConfig,
    UserManagerSecurity,
    is_authenticated,
)
from litestar_auth.authentication.strategy import JWTStrategy
from litestar_auth.db.sqlalchemy import SQLAlchemyUserDatabase
from litestar_auth.models import User

DATABASE_URL = "sqlite+aiosqlite:///./quickstart.db"
JWT_SECRET = os.environ["LITESTAR_AUTH_JWT_SECRET"]
RESET_PASSWORD_TOKEN_SECRET = os.environ["LITESTAR_AUTH_RESET_PASSWORD_TOKEN_SECRET"]
VERIFY_TOKEN_SECRET = os.environ["LITESTAR_AUTH_VERIFY_TOKEN_SECRET"]

engine = create_async_engine(DATABASE_URL, echo=False)
session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


class UserManager(BaseUserManager[User, UUID]):
    """Print verification tokens so the quickstart can finish without email infrastructure."""

    verification_tokens: dict[str, str] = {}

    async def on_after_register(self, user: User, token: str) -> None:
        self.verification_tokens[user.email] = token
        print(f"verification token for {user.email}: {token}")  # noqa: T201


@get("/protected", guards=[is_authenticated])
async def protected(request: Request[User, Any, Any]) -> dict[str, str]:
    user = request.user
    assert user is not None
    return {"email": user.email}


backend = AuthenticationBackend[User, UUID](
    name="bearer",
    transport=BearerTransport(),
    strategy=JWTStrategy[User, UUID](
        secret=JWT_SECRET,
        lifetime=timedelta(minutes=15),
        subject_decoder=UUID,
        allow_inmemory_denylist=True,
    ),
)

config = LitestarAuthConfig[User, UUID](
    backends=(backend,),
    session_maker=session_maker,
    user_model=User,
    user_manager_class=UserManager,
    user_db_factory=lambda session: SQLAlchemyUserDatabase(session, user_model=User),
    user_manager_security=UserManagerSecurity(
        verification_token_secret=VERIFY_TOKEN_SECRET,
        reset_password_token_secret=RESET_PASSWORD_TOKEN_SECRET,
    ),
    include_users=False,
)

app = Litestar(route_handlers=[protected], plugins=[LitestarAuth(config)])

Features

  • Litestar-native plugin setup through LitestarAuthConfig(...) and LitestarAuth(config).
  • Registration, login, email verification, password reset, and protected-route guards out of the box.
  • Transport + strategy auth backends, including Bearer or Cookie transports and JWT, database, or Redis token strategies.
  • Opt-in DB-backed session/device routes for listing active refresh sessions and revoking one session or all other sessions without exposing raw tokens or token digests.
  • BaseUserManager hooks for integrating email delivery, background jobs, and app-specific lifecycle logic.
  • Bundled SQLAlchemy user model plus SQLAlchemyUserDatabase for the default persistence path.
  • Normalized flat-role contract for responses and guards, with a matching litestar roles CLI for operator workflows.
  • Optional Redis denylist, rate limiting, OAuth login/account linking, and built-in TOTP support.
  • Typed public APIs and docs aimed at application developers rather than framework internals.

Install

uv add litestar-auth
# or
pip install litestar-auth

For the SQLite quick peek and quickstart example, also add aiosqlite:

uv add litestar-auth aiosqlite

Install extras only when you need those features:

  • litestar-auth[redis] for Redis-backed token storage, JWT denylist support, and auth rate limiting.
  • litestar-auth[oauth] for OAuth flows via httpx-oauth and encrypted provider tokens.
  • litestar-auth[totp] for built-in TOTP helpers.
  • litestar-auth[all] for redis, oauth, and totp together.

Requirements

See the Migration Guide for Litestar 2.22 route-parameter conventions and Advanced Alchemy 1.10 repository API changes.

Password hashing defaults are now Argon2-only. Unsupported stored password hashes fail closed under the library default, so rotate or reset those credentials before upgrading; see the Migration Guide.

Runnable examples

This repository ships small Litestar apps under examples/ (not published on PyPI). Each package documents its own environment variables; local demos typically set ..._INSECURE=1 as noted there.

Install an ASGI server (for example uvicorn), then pick a scenario from the table in examples/__init__.py.

Bearer JWT + TOTP sketch (demo_totp):

export LITESTAR_AUTH_DEMO_TOTP_INSECURE=1
uv run uvicorn examples.demo_totp.app:app --host 127.0.0.1 --port 8000
# curl http://127.0.0.1:8000/health
# curl -sS -X POST http://127.0.0.1:8000/auth/register \
#   -H 'Content-Type: application/json' \
#   -d '{"email":"you@example.com","password":"choose-a-strong-password"}'

Cookie + CSRF flows (demo_cookie_jwt, demo_cookie_jwt_totp) need a client that keeps cookies and sends X-CSRF-Token on unsafe methods after loading /health.

Read more

  • Quickstart: bootstrap SQLite, run the app, and walk through register/verify/login.
  • Installation: requirements, extras, and typical deployment stacks.
  • Configuration: user model, manager, backends, Redis, OAuth, TOTP, and security knobs.
  • HTTP API: generated routes, including the opt-in DB refresh-session/device management surface.
  • Security: secure defaults, migration-only flags, and production hardening notes.
  • Deployment security checklist: reverse-proxy trust, cookie transport, and secrets-at-rest preconditions.
  • Role management CLI: operator commands for bundled relational roles.
  • Testing plugin-backed apps: AsyncTestClient patterns and repo-aligned test advice.
  • Python API overview: stable imports and where advanced submodules live.

Repository

Contributor setup, verification commands, and docs tooling live in Contributing.

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

litestar_auth-5.0.1.tar.gz (1.5 MB view details)

Uploaded Source

Built Distribution

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

litestar_auth-5.0.1-py3-none-any.whl (493.0 kB view details)

Uploaded Python 3

File details

Details for the file litestar_auth-5.0.1.tar.gz.

File metadata

  • Download URL: litestar_auth-5.0.1.tar.gz
  • Upload date:
  • Size: 1.5 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for litestar_auth-5.0.1.tar.gz
Algorithm Hash digest
SHA256 c46721b8a5eabfb86de2a83d07eb8fd124d0b853632f0331d5a8c7b997ba3132
MD5 cb117f6ab53e562772d93f1e254f3f7d
BLAKE2b-256 c14684e5e8359b287306c05a54919b9dd0608a5df6fd765508e2ccc9a4855ec4

See more details on using hashes here.

Provenance

The following attestation bundles were made for litestar_auth-5.0.1.tar.gz:

Publisher: 3_release.yml on ZYLVEXT/litestar-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 litestar_auth-5.0.1-py3-none-any.whl.

File metadata

  • Download URL: litestar_auth-5.0.1-py3-none-any.whl
  • Upload date:
  • Size: 493.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for litestar_auth-5.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a99e114cb36c1ccc96200746d9e3e7cb98eaa9c971391fb022625e0ac4a26dfc
MD5 b8e86c81f06424ee4fcb1bce3226402c
BLAKE2b-256 ef54922a6591fa8d5adcc5615b178550f2ce0396e4004518a0fff16d5b922021

See more details on using hashes here.

Provenance

The following attestation bundles were made for litestar_auth-5.0.1-py3-none-any.whl:

Publisher: 3_release.yml on ZYLVEXT/litestar-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