Skip to content

Quickstart

This walkthrough wires one authentication backend: Bearer transport + JWT strategy, with the default SQLAlchemy user model from litestar_auth.models.

1. Dependencies

Install the library and an async SQLite driver if you follow the snippet literally:

uv add litestar-auth aiosqlite

For PostgreSQL or MySQL, use the appropriate sqlalchemy async driver instead.

2. Create tables

The bundled User model (and related token/OAuth tables if you use those features) must exist in your database. Use Alembic or metadata.create_all in a migration — not shown here.

3. Application code

The following matches the pattern used in the test suite: build a LitestarAuthConfig, pass it to LitestarAuth, and register the plugin on Litestar.

"""Minimal wiring pattern: JWT + Bearer backend and LitestarAuth plugin.

Replace secrets and database URL. For SQLite async you need `aiosqlite`.
This file is included in docs via pymdownx.snippets; it is not part of the installed package.
"""

from __future__ import annotations

from datetime import timedelta
from uuid import UUID

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

from litestar_auth import (
    BaseUserManager,
    LitestarAuth,
    LitestarAuthConfig,
    PasswordHelper,
    SQLAlchemyUserDatabase,
)
from litestar_auth.authentication.backend import AuthenticationBackend
from litestar_auth.authentication.strategy import JWTStrategy
from litestar_auth.authentication.transport import BearerTransport
from litestar_auth.models import User


DATABASE_URL = "sqlite+aiosqlite:///./auth.db"
engine = create_async_engine(DATABASE_URL, echo=False)
session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


class UserManager(BaseUserManager[User, UUID]):
    """Override hooks (on_after_register, etc.) as needed."""


def build_app() -> Litestar:
    jwt_strategy = JWTStrategy[User, UUID](
        secret="replace-with-32+-char-jwt-secret",
        lifetime=timedelta(minutes=15),
        subject_decoder=UUID,
    )
    backend = AuthenticationBackend[User, UUID](
        name="jwt",
        transport=BearerTransport(),
        strategy=jwt_strategy,
    )
    config = LitestarAuthConfig(
        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_kwargs={
            "password_helper": PasswordHelper(),
            "verification_token_secret": "replace-with-32+-char-secret-for-verify",
            "reset_password_token_secret": "replace-with-32+-char-secret-for-reset",
        },
        include_users=False,
    )
    return Litestar(plugins=[LitestarAuth(config)])

4. Provide a database session

  • session_maker is a callable factory the plugin invokes as session_maker() to obtain the shared request-local AsyncSession. The snippet uses async_sessionmaker(...), which is the common implementation.
  • session_maker set (as in the snippet above): the plugin registers a request-scoped AsyncSession provider under LitestarAuthConfig.db_session_dependency_key (default db_session). You do not need to wire that dependency yourself.
  • Your app already provides a session: set db_session_dependency_provided_externally=True and ensure something else injects AsyncSession under the same key (or change the key with db_session_dependency_key).
  • Custom dependency name only: keep session_maker and set db_session_dependency_key to match your handlers’ parameter name.

5. Call the API

With defaults, log in at POST /auth/login and send Authorization: Bearer <access_token> on protected routes. See HTTP API for the full surface.

Next steps