Strategies¶
litestar_auth.authentication.strategy
¶
Issue, validate, rotate, and revoke tokens (JWT, database, or Redis).
Strategies pair with :mod:litestar_auth.authentication.transport implementations
inside :class:~litestar_auth.authentication.backend.AuthenticationBackend.
DatabaseTokenModels is the explicit contract for DatabaseTokenStrategy when you swap in
mixin-composed token ORM classes. import_token_orm_models() remains re-exported here only for
compatibility with existing imports; the canonical public bootstrap helper lives at
litestar_auth.models.import_token_orm_models().
DatabaseTokenModels(access_token_model=AccessToken, refresh_token_model=RefreshToken)
dataclass
¶
Explicit access-token and refresh-token ORM contract for DatabaseTokenStrategy.
The supplied models must expose mapped token, created_at, user_id, and user
attributes compatible with the persistence operations performed by the DB token strategy.
Defaults preserve the bundled AccessToken / RefreshToken behavior.
__post_init__()
¶
Validate the supplied token-model classes eagerly.
Source code in litestar_auth/authentication/strategy/db_models.py
DatabaseTokenStrategy(*, session, token_hash_secret, token_models=None, max_age=DEFAULT_MAX_AGE, refresh_max_age=DEFAULT_REFRESH_MAX_AGE, token_bytes=DEFAULT_TOKEN_BYTES, accept_legacy_plaintext_tokens=False)
¶
Bases: Strategy[UP, ID], RefreshableStrategy[UP, ID]
Stateful strategy that persists opaque tokens in the database.
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
AsyncSessionT
|
SQLAlchemy session used by the repository. |
required |
token_hash_secret
|
str
|
High-entropy secret used for keyed token hashing (HMAC-SHA256). |
required |
token_models
|
DatabaseTokenModels | None
|
Access-token and refresh-token ORM models used for persistence. Omit to
keep the bundled |
None
|
max_age
|
timedelta
|
Maximum token age before it is rejected. |
DEFAULT_MAX_AGE
|
refresh_max_age
|
timedelta
|
Maximum refresh-token age before it is rejected. |
DEFAULT_REFRESH_MAX_AGE
|
token_bytes
|
int
|
Number of random bytes used for token generation. |
DEFAULT_TOKEN_BYTES
|
accept_legacy_plaintext_tokens
|
bool
|
When enabled, accept previously persisted raw tokens stored before digest-at-rest hardening. This is intended for migrations only. |
False
|
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
When |
Source code in litestar_auth/authentication/strategy/db.py
cleanup_expired_tokens(session)
async
¶
Delete expired access and refresh tokens for the configured TTLs.
Returns:
| Type | Description |
|---|---|
int
|
Total number of deleted access-token and refresh-token rows. |
Source code in litestar_auth/authentication/strategy/db.py
destroy_token(token, user)
async
¶
Delete a persisted token.
Source code in litestar_auth/authentication/strategy/db.py
invalidate_all_tokens(user)
async
¶
Delete all persisted access and refresh tokens for the given user.
Source code in litestar_auth/authentication/strategy/db.py
read_token(token, user_manager)
async
¶
Resolve a user from an opaque database token.
Returns:
| Type | Description |
|---|---|
UP | None
|
Related user when the token exists and is not expired, otherwise |
Source code in litestar_auth/authentication/strategy/db.py
rotate_refresh_token(refresh_token, user_manager)
async
¶
Rotate a refresh token and return the related user plus replacement.
Returns:
| Type | Description |
|---|---|
tuple[UP, str] | None
|
Tuple of the resolved user and rotated refresh token, or |
Source code in litestar_auth/authentication/strategy/db.py
with_session(session)
¶
Return a copy of the strategy bound to the provided async session.
Source code in litestar_auth/authentication/strategy/db.py
write_refresh_token(user)
async
¶
Persist and return a new opaque refresh token for the user.
Returns:
| Type | Description |
|---|---|
str
|
Newly created opaque refresh-token string. |
Source code in litestar_auth/authentication/strategy/db.py
write_token(user)
async
¶
Persist and return a new opaque token for the user.
Returns:
| Type | Description |
|---|---|
str
|
Newly created opaque token string. |
Source code in litestar_auth/authentication/strategy/db.py
JWTStrategy(*, secret, verify_key=None, algorithm=DEFAULT_ALGORITHM, lifetime=DEFAULT_LIFETIME, subject_decoder=None, issuer=None, denylist_store=None, session_fingerprint_getter=None, session_fingerprint_claim='sfp')
¶
Bases: Strategy[UP, ID]
Stateless strategy that stores user identifiers inside JWTs.
JWT access tokens issued by this strategy are designed to be short-lived
and stateless. This implementation also maintains a lightweight, in-memory
denylist keyed by the jti claim so that individual tokens can be
explicitly revoked before expiration when :meth:destroy_token is called.
The in-memory denylist is process-local and is not persisted across worker restarts; deployments that require stronger revocation guarantees should wrap or subclass this strategy and back the denylist with a shared store such as Redis.
Initialize the JWT strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Signing secret or private key used for JWT encoding. |
required |
verify_key
|
str | None
|
Optional verification key used for JWT decoding. When
omitted, |
None
|
algorithm
|
str
|
JWT signing algorithm. |
DEFAULT_ALGORITHM
|
lifetime
|
timedelta
|
Token lifetime added to the expiration claim. |
DEFAULT_LIFETIME
|
subject_decoder
|
Callable[[str], ID] | None
|
Optional callable that converts the |
None
|
issuer
|
str | None
|
Optional issuer string to embed in the |
None
|
denylist_store
|
JWTDenylistStore | None
|
Optional shared denylist backend for durable token revocation across workers. |
None
|
session_fingerprint_getter
|
Callable[[UP], str | None] | None
|
Optional callable that returns a fingerprint representing a user's current security state. When the returned value is embedded into tokens, password/email changes can invalidate old tokens without server-side session storage. |
None
|
session_fingerprint_claim
|
str
|
JWT claim name used to store the session fingerprint. |
'sfp'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the configured algorithm is not allow-listed. |
Source code in litestar_auth/authentication/strategy/jwt.py
revocation_is_durable
property
¶
Return whether token revocation is backed by a shared store.
destroy_token(token, user)
async
¶
Revoke the given token by adding its jti to the denylist.
The denylist is maintained in memory on the strategy instance. Tokens
without a jti claim, or tokens that fail to decode, are ignored.
Source code in litestar_auth/authentication/strategy/jwt.py
read_token(token, user_manager)
async
¶
Decode a JWT token and load its user.
Returns:
| Type | Description |
|---|---|
UP | None
|
The matching user, or |
Source code in litestar_auth/authentication/strategy/jwt.py
write_token(user)
async
¶
Generate a JWT token for the provided user.
Returns:
| Type | Description |
|---|---|
str
|
The encoded JWT token string. |
Source code in litestar_auth/authentication/strategy/jwt.py
RedisTokenStrategy(*, redis, token_hash_secret, lifetime=DEFAULT_LIFETIME, token_bytes=DEFAULT_TOKEN_BYTES, key_prefix=DEFAULT_KEY_PREFIX, subject_decoder=None, max_scan_keys=DEFAULT_MAX_SCAN_KEYS)
¶
Bases: Strategy[UP, ID]
Stateful strategy that stores opaque tokens in Redis with TTL.
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisClientProtocol
|
Async Redis client compatible with |
required |
token_hash_secret
|
str
|
High-entropy secret used for keyed token hashing (HMAC-SHA256). |
required |
lifetime
|
timedelta
|
Token TTL applied to persisted keys. |
DEFAULT_LIFETIME
|
token_bytes
|
int
|
Number of random bytes used for token generation. |
DEFAULT_TOKEN_BYTES
|
key_prefix
|
str
|
Prefix used to namespace token keys in Redis. |
DEFAULT_KEY_PREFIX
|
subject_decoder
|
Callable[[str], ID] | None
|
Optional callable that converts the stored user id string into the identifier type expected by the user manager. |
None
|
max_scan_keys
|
int
|
Safety cap on keys examined during scan-based fallback invalidation. Prevents runaway iteration on large keyspaces. |
DEFAULT_MAX_SCAN_KEYS
|
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
When |
Source code in litestar_auth/authentication/strategy/redis.py
destroy_token(token, user)
async
¶
Delete a persisted Redis token.
Source code in litestar_auth/authentication/strategy/redis.py
invalidate_all_tokens(user)
async
¶
Delete all Redis-backed tokens associated with the given user.
This uses a per-user index to delete only the keys associated with the user, avoiding keyspace scans under the global prefix.
Backward compatibility
If the per-user index is missing, we fall back to a best-effort scan
over keys matching the configured prefix and remove those whose
stored subject matches user.id.
Source code in litestar_auth/authentication/strategy/redis.py
read_token(token, user_manager)
async
¶
Resolve a user from a Redis-backed token.
Returns:
| Type | Description |
|---|---|
UP | None
|
The resolved user when the token exists and decodes successfully, |
UP | None
|
otherwise |
Source code in litestar_auth/authentication/strategy/redis.py
write_token(user)
async
¶
Persist a new opaque token in Redis and return it.
Returns:
| Type | Description |
|---|---|
str
|
Newly created opaque token string. |
Source code in litestar_auth/authentication/strategy/redis.py
RefreshableStrategy
¶
Bases: Protocol
Protocol for strategies that support refresh-token rotation.
Note
Refresh tokens are intentionally modeled as a separate lifecycle artifact from
access tokens. In particular, Strategy.destroy_token() only targets the access
token used for request authentication; refresh-token invalidation (if any) is
managed by the refresh strategy itself.
rotate_refresh_token(refresh_token, user_manager)
async
¶
Consume a refresh token and return the user plus a rotated replacement.
Strategy
¶
UserManagerProtocol
¶
import_token_orm_models()
¶
Return the bundled token ORM models for compatibility and low-level imports.
Prefer litestar_auth.models.import_token_orm_models() for public explicit mapper
registration. This module-level helper remains available for strategy-layer compatibility.