Redis contrib¶
Use Configuration for the main
Redis-backed auth story: the shared-client preset flow, the AuthRateLimitSlot enum,
namespace families, migration behavior, and TOTP store guidance still live there.
litestar_auth.contrib.redis is the higher-level entrypoint when one async Redis client should back
auth rate limiting plus the TOTP Redis stores:
RedisAuthClientProtocolis the stable typing contract for annotating the shared async Redis client passed toRedisAuthPreset.RedisAuthPresetbuildsAuthRateLimitConfig,RedisTotpEnrollmentStore,RedisUsedTotpCodeStore, and the pending-tokenRedisJWTDenylistStorehelper from one shared client and per-group rate-limit tiers. UseRedisAuthRateLimitConfigOptionswhen callingbuild_rate_limit_config(...)withenabled=...ordisabled=.... The shared-client contract covers the combined operations used by the rate-limiter, pending-enrollment, used-code replay, and pending-JTI denylist helpers:eval(...),delete(...),set(name, value, nx=True, px=ttl_ms),set(name, value, ex=ttl_s), andget(...).RedisTokenStrategy,RedisTokenStrategyConfig,RedisTotpEnrollmentStore, andRedisUsedTotpCodeStoreremain the direct low-level convenience imports.AuthRateLimitConfig.from_shared_backend(), directRedisRateLimiter(...)construction, and directRedisJWTDenylistStore(...)/RedisTotpEnrollmentStore(...)/RedisUsedTotpCodeStore(...)construction remain the fallback low-level path for applications that need separate backends or fully bespoke wiring.RedisApiKeyNonceStoreis the shared-store nonce backend for signed API-key replay protection. Use it instead ofInMemoryApiKeyNonceStorein multi-worker deployments.
Optional Redis-backed helpers (requires litestar-auth[redis]).
litestar_auth.contrib.redis
¶
Stable public Redis contrib helpers.
This package exposes the documented shared-client Redis typing contract, the shared-client preset, and the current low-level Redis-backed auth convenience imports.
RedisApiKeyNonceStore(*, redis, key_prefix=DEFAULT_API_KEY_NONCE_PREFIX)
¶
Redis-backed API-key signing nonce store.
Store the Redis client and key namespace.
Source code in litestar_auth/authentication/strategy/_api_key_nonce_store.py
is_shared_across_workers
property
¶
Redis state is shared across workers using the same server.
mark_used(*, key_id, nonce, ttl_seconds)
async
¶
Atomically record a nonce with SET NX PX.
Returns:
| Type | Description |
|---|---|
ApiKeyNonceStoreResult
|
Stored/replay outcome for the nonce insert. |
Source code in litestar_auth/authentication/strategy/_api_key_nonce_store.py
RedisApiKeyNonceStoreClient
¶
Bases: RedisConditionalSetClient, Protocol
Minimal Redis client for API-key signing nonce storage.
RedisAuthClientProtocol
¶
Bases: RedisSharedAuthClient, Protocol
Public async Redis client contract shared by Redis auth contrib helpers.
RedisAuthPreset(redis, rate_limit_tier=_default_rate_limit_tier(), group_rate_limit_tiers=_empty_group_rate_limit_tiers(), totp_used_tokens_key_prefix=None, totp_pending_jti_key_prefix=None, totp_enrollment_key_prefix=None)
dataclass
¶
Shared-client Redis preset for auth rate limiting and TOTP state stores.
Keep the low-level RedisRateLimiter, RedisUsedTotpCodeStore,
RedisTotpEnrollmentStore, RedisJWTDenylistStore, and
AuthRateLimitConfig.from_shared_backend() APIs for advanced cases that
need fully custom backends. This preset is the higher-level path when one
async Redis client should back the auth rate-limit config plus the TOTP
replay, pending-enrollment, and pending-token replay stores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisAuthClientProtocol
|
Async Redis client compatible with |
required |
rate_limit_tier
|
RedisAuthRateLimitTier
|
Default rate-limit settings used for every supported auth slot unless a group-specific override is configured. |
_default_rate_limit_tier()
|
group_rate_limit_tiers
|
Mapping[AuthRateLimitEndpointGroup, RedisAuthRateLimitTier]
|
Optional per-group rate-limit settings keyed by
|
_empty_group_rate_limit_tiers()
|
totp_used_tokens_key_prefix
|
str | None
|
Optional default Redis key prefix for the
TOTP replay store. |
None
|
totp_pending_jti_key_prefix
|
str | None
|
Optional default Redis key prefix for the
pending-login-token JTI denylist store. |
None
|
totp_enrollment_key_prefix
|
str | None
|
Optional default Redis key prefix for the
pending-enrollment store. |
None
|
__post_init__()
¶
Snapshot group-specific rate-limit tiers into a read-only mapping.
build_rate_limit_config(*, options=None)
¶
Build AuthRateLimitConfig from the preset's shared Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options
|
RedisAuthRateLimitConfigOptions | None
|
Optional shared builder options. When omitted, every supported auth slot uses the preset's default tier. |
None
|
Returns:
| Type | Description |
|---|---|
AuthRateLimitConfig
|
The auth rate-limit config built from the preset's shared client and |
AuthRateLimitConfig
|
tier settings. |
Source code in litestar_auth/contrib/redis/_surface.py
build_totp_enrollment_store(*, key_prefix=None)
¶
Build RedisTotpEnrollmentStore from the preset's shared Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_prefix
|
str | None
|
Optional per-call Redis key prefix override. When
omitted, the preset uses |
None
|
Returns:
| Type | Description |
|---|---|
RedisTotpEnrollmentStore
|
Redis-backed pending-enrollment store sharing the preset's client. |
Source code in litestar_auth/contrib/redis/_surface.py
build_totp_pending_jti_store(*, key_prefix=None)
¶
Build RedisJWTDenylistStore from the preset's shared Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_prefix
|
str | None
|
Optional per-call Redis key prefix override. When
omitted, the preset uses |
None
|
Returns:
| Type | Description |
|---|---|
RedisJWTDenylistStore
|
Redis-backed pending-token JTI denylist sharing the preset's |
RedisJWTDenylistStore
|
client. |
Source code in litestar_auth/contrib/redis/_surface.py
build_totp_used_tokens_store(*, key_prefix=None)
¶
Build RedisUsedTotpCodeStore from the preset's shared Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_prefix
|
str | None
|
Optional per-call Redis key prefix override. When
omitted, the preset uses |
None
|
Returns:
| Type | Description |
|---|---|
RedisUsedTotpCodeStore
|
Redis-backed TOTP replay store sharing the preset's client. |
Source code in litestar_auth/contrib/redis/_surface.py
RedisAuthRateLimitConfigOptions(enabled=None, disabled=(), group_backends=None, endpoint_overrides=None, trusted_proxy=False, identity_fields=None, trusted_headers=None, trusted_proxy_hops=1)
dataclass
¶
Builder options for :meth:RedisAuthPreset.build_rate_limit_config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
Iterable[AuthRateLimitSlot] | None
|
Optional auth slot enum values to build. |
None
|
disabled
|
Iterable[AuthRateLimitSlot]
|
Auth slot enum values to leave unset. |
()
|
group_backends
|
Mapping[AuthRateLimitEndpointGroup, RateLimiterBackend] | None
|
Optional explicit backend overrides keyed by auth slot
group. These win over |
None
|
endpoint_overrides
|
Mapping[AuthRateLimitSlot, EndpointRateLimit | None] | None
|
Optional full per-slot replacements or explicit
|
None
|
trusted_proxy
|
bool
|
Shared trusted-proxy setting applied to generated limiters. |
False
|
identity_fields
|
tuple[str, ...] | None
|
Optional shared request body identity fields. When
omitted, |
None
|
trusted_headers
|
tuple[str, ...] | None
|
Optional shared trusted proxy header names. When
omitted, |
None
|
trusted_proxy_hops
|
int
|
Shared X-Forwarded-For hop count applied to generated limiters. |
1
|
RedisAuthRateLimitTier(max_attempts, window_seconds, key_prefix=None)
dataclass
¶
Rate-limit settings used by :class:RedisAuthPreset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Maximum attempts allowed inside the window. |
required |
window_seconds
|
float
|
Sliding-window duration in seconds. |
required |
key_prefix
|
str | None
|
Optional Redis key prefix passed to |
None
|
RedisTokenStrategy(*, config=None, **options)
¶
Bases: Strategy[UP, ID]
Stateful strategy that stores opaque tokens in Redis with TTL.
Initialize the strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RedisTokenStrategyConfig[ID] | None
|
Redis strategy configuration. |
None
|
**options
|
Unpack[RedisTokenStrategyOptions[ID]]
|
Individual Redis strategy settings. Do not combine with
|
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
has_recent_totp_verification(user, session_id)
async
¶
Return whether a Redis-backed session has a live TOTP step-up marker.
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 bumps a per-user invalidation epoch before deleting indexed token and step-up marker keys, so out-of-index tokens are rejected on their next read without requiring a keyspace scan.
Source code in litestar_auth/authentication/strategy/redis.py
issue_totp_stepup(user, session_id, *, ttl_seconds)
async
¶
Store a short-lived TOTP step-up marker for a Redis-backed session.
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
RedisTokenStrategyConfig(redis, token_hash_secret, lifetime=DEFAULT_LIFETIME, token_bytes=DEFAULT_TOKEN_BYTES, key_prefix=DEFAULT_KEY_PREFIX, subject_decoder=None)
dataclass
¶
Configuration for :class:RedisTokenStrategy.