Authentication (middleware, authenticator, backend)¶
An AuthenticationBackend pairs a transport with a strategy: the transport reads token material from the request (for example Authorization: Bearer or cookies), and the strategy validates or issues tokens and resolves the user through the user manager. Login and logout flow through the same pair so issuing, invalidation, and response shaping stay consistent.
An Authenticator holds an ordered list of backends plus a UserManagerProtocol. For each request it tries backends in order and returns the first user that authenticates, so you can stack transports (Bearer plus cookie, multiple named backends, and so on) without duplicating strategy wiring.
API-key backends use ApiKeyTransport with ApiKeyStrategy. Successful API-key authentication
sets request.auth to ApiKeyContext rather than the backend name string, so scope guards can
inspect the authenticated key id, prefix environment, and key scopes.
LitestarAuthMiddleware plugs the authenticator into Litestar’s ASGI pipeline so connection.user and related auth state are populated from the same backend list your routes and guards use.
Signed API-key requests need pre-auth body buffering so the HMAC check can commit to the raw request
body. Plugin-managed applications opt into that buffering automatically when the startup backend
inventory includes an ApiKeyTransport. Direct integrations that construct LitestarAuthMiddleware
outside the plugin fail closed by default: LitestarAuthMiddlewareConfig.api_key_backend_present
defaults to False, so signed-body buffering is skipped unless you pass
api_key_backend_present=True for a backend list that contains an ApiKeyTransport.
For diagrams, transport vs strategy tables, and plugin-oriented setup, see Backends: transports and strategies.
from litestar_auth.authentication import (
AuthenticationBackend,
Authenticator,
LitestarAuthMiddleware,
)
# Typical wiring: build AuthenticationBackend(name, transport, strategy) instances,
# wrap them in Authenticator(backends, user_manager), then register LitestarAuthMiddleware.
litestar_auth.authentication
¶
Authentication package.
AuthenticationBackend(*, name, transport, strategy)
¶
Compose a transport and strategy into a reusable auth backend.
Store backend components used for auth flows.
Source code in litestar_auth/authentication/backend.py
authenticate(connection, user_manager)
async
¶
Resolve a user from the current request via transport and strategy.
Returns:
| Type | Description |
|---|---|
UP | None
|
Authenticated user or |
Source code in litestar_auth/authentication/backend.py
authenticate_with_context(connection, user_manager)
async
¶
Resolve a user and request auth context from the current request.
Returns:
| Type | Description |
|---|---|
tuple[UP, object] | None
|
Authenticated user plus request auth context, or |
Source code in litestar_auth/authentication/backend.py
login(user)
async
¶
Issue a token through the configured strategy and transport.
Returns:
| Type | Description |
|---|---|
Response[Any]
|
Response mutated by the configured transport for login. |
Source code in litestar_auth/authentication/backend.py
logout(user, token)
async
¶
Invalidate a token and clear transport-managed state.
When the transport is a :class:CookieTransport, the refresh-token
cookie is also expired so the browser does not retain it after logout.
Returns:
| Type | Description |
|---|---|
Response[Any]
|
Response mutated by the configured transport for logout. |
Raises:
| Type | Description |
|---|---|
ClientException
|
When token revocation cannot be recorded (for example, an
in-memory denylist at capacity), surfaced as HTTP 503 with the library
error |
Source code in litestar_auth/authentication/backend.py
terminate_session(connection, user)
async
¶
Terminate the current authenticated session for a connection.
This method orchestrates logout in one explicit place by reading the
current transport token and delegating token invalidation plus transport
cleanup to logout.
Returns:
| Type | Description |
|---|---|
Response[Any]
|
Response mutated by the configured transport for logout. |
Raises:
| Type | Description |
|---|---|
NotAuthorizedException
|
If the current transport token is unavailable. |
Source code in litestar_auth/authentication/backend.py
with_session(session)
¶
Return a backend whose strategy is rebound to the provided session when supported.
Source code in litestar_auth/authentication/backend.py
Authenticator(backends, user_manager)
¶
Try configured authentication backends in order.
Store backends and the user manager used for token resolution.
Source code in litestar_auth/authentication/authenticator.py
authenticate(connection)
async
¶
Return the first authenticated user and request auth context.
Returns:
| Type | Description |
|---|---|
UP | None
|
Tuple of authenticated user and request auth context, or |
object | None
|
when no backend resolves the request. |
Source code in litestar_auth/authentication/authenticator.py
LitestarAuthMiddleware(app, *, config=None, **options)
¶
Bases: AbstractAuthenticationMiddleware
Resolve request users through an authenticator built with the request-scoped DB session.
Initialize the middleware.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
ASGIApp
|
ASGI app to wrap. |
required |
config
|
LitestarAuthMiddlewareConfig[UP, ID] | None
|
Middleware runtime configuration. |
None
|
**options
|
Unpack[LitestarAuthMiddlewareOptions[UP, ID]]
|
Individual middleware settings. Do not combine with
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in litestar_auth/authentication/middleware.py
__call__(scope, receive, send)
async
¶
Buffer signed request bodies before authentication so signatures cover raw bytes.
Source code in litestar_auth/authentication/middleware.py
authenticate_request(connection)
async
¶
Authenticate the request and return the resolved user or None.
Returns:
| Type | Description |
|---|---|
AuthenticationResult
|
Authentication result containing the resolved user and backend name. |
Source code in litestar_auth/authentication/middleware.py
LitestarAuthMiddlewareConfig(get_request_session, authenticator_factory, auth_cookie_names=frozenset(), api_key_use_rate_limit=None, api_key_backend_present=False, api_key_signed_body_max_bytes=_DEFAULT_API_KEY_SIGNED_BODY_MAX_BYTES, api_key_signed_body_max_messages=_DEFAULT_API_KEY_SIGNED_BODY_MAX_MESSAGES, superuser_role_name=DEFAULT_SUPERUSER_ROLE_NAME, exclude=None, exclude_from_auth_key='exclude_from_auth', exclude_http_methods=None, scopes=None)
dataclass
¶
Configuration for :class:LitestarAuthMiddleware.