Redis contrib¶
Use Configuration for the canonical
Redis-backed auth story: the preferred one-client preset flow, the AUTH_RATE_LIMIT_* helper
exports, namespace families, migration behavior, and TOTP replay-store guidance still live there.
litestar_auth.contrib.redis is the higher-level entrypoint when one async Redis client should back
both auth rate limiting and TOTP replay protection:
RedisAuthPresetbuildsAuthRateLimitConfigplusRedisUsedTotpCodeStorefrom one shared client and per-group rate-limit tiers. Import slot helpers such asAUTH_RATE_LIMIT_VERIFICATION_SLOTSfromlitestar_auth.ratelimitwhen callingbuild_rate_limit_config(...). The shared client only needs the combinedRedisRateLimiter+RedisUsedTotpCodeStoreoperations:eval(...),delete(...), andset(name, value, nx=True, px=ttl_ms).RedisTokenStrategyandRedisUsedTotpCodeStoreremain the direct low-level convenience imports.AuthRateLimitConfig.from_shared_backend()and directRedisRateLimiter(...)construction remain the fallback escape hatches for applications that need separate backends or fully bespoke wiring.
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 preset plus the current low-level Redis-backed auth convenience imports.
RedisAuthPreset(redis, rate_limit_tier=_default_rate_limit_tier(), group_rate_limit_tiers=dict(), totp_used_tokens_key_prefix=None)
dataclass
¶
Shared-client Redis preset for auth rate limiting and TOTP replay protection.
Keep the low-level RedisRateLimiter, RedisUsedTotpCodeStore, 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 both the auth rate-limit config and the TOTP
replay store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisSharedAuthClient
|
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
|
dict()
|
totp_used_tokens_key_prefix
|
str | None
|
Optional default Redis key prefix for the
TOTP replay store. |
None
|
build_rate_limit_config(*, enabled=None, disabled=(), group_backends=None, scope_overrides=None, namespace_style='route', namespace_overrides=None, endpoint_overrides=None, trusted_proxy=False, identity_fields=None, trusted_headers=None)
¶
Build AuthRateLimitConfig from the preset's shared Redis client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
Iterable[AuthRateLimitEndpointSlot] | None
|
Optional auth slot names to build. |
None
|
disabled
|
Iterable[AuthRateLimitEndpointSlot]
|
Auth slot names to leave unset. |
()
|
group_backends
|
Mapping[AuthRateLimitEndpointGroup, RateLimiterBackend] | None
|
Optional explicit backend overrides keyed by auth
slot group. These win over |
None
|
scope_overrides
|
Mapping[AuthRateLimitEndpointSlot, RateLimitScope] | None
|
Optional per-slot scope overrides. |
None
|
namespace_style
|
AuthRateLimitNamespaceStyle
|
Namespace family for generated limiters. |
'route'
|
namespace_overrides
|
Mapping[AuthRateLimitEndpointSlot, str] | None
|
Optional per-slot namespace overrides. |
None
|
endpoint_overrides
|
Mapping[AuthRateLimitEndpointSlot, 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
|
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
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
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
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(*, 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
RedisUsedTotpCodeStore(*, redis, key_prefix=DEFAULT_TOTP_USED_KEY_PREFIX)
¶
Redis-backed replay store for TOTP codes; safe for multi-worker and multi-pod deployments.
For the higher-level shared-client Redis preset that can also derive
AuthRateLimitConfig, see litestar_auth.contrib.redis.RedisAuthPreset.
Store the Redis client and key prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
RedisUsedTotpCodeStoreClient
|
Async Redis client supporting |
required |
key_prefix
|
str
|
Prefix for replay keys; keys are |
DEFAULT_TOTP_USED_KEY_PREFIX
|
Source code in litestar_auth/totp.py
mark_used(user_id, counter, ttl_seconds)
async
¶
Atomically record a used (user_id, counter) pair via SET key 1 NX PX ttl_ms.
Returns:
| Type | Description |
|---|---|
bool
|
|