keepcalculator

06 Numbers and Powers

Refresh Token Replay: What Redis Must Do to Revoke Safely

Card No. 06·80822 · Updated · Standard formula, shown below

Refresh token replay attacks happen when a stolen or leaked refresh token is used to obtain a new access token after the legitimate user has already used it. To revoke safely, Redis must store a hash of each valid refresh token, check it on every refresh, and atomically delete or rotate it on first use, so a replayed token is rejected. This article explains the exact Redis data structures, commands, and policies needed to make revocation reliable and race-condition-free.

Why Refresh Tokens Are a Replay Target

Refresh tokens are long-lived credentials that let a client get new access tokens without asking the user to log in again. Because they are sent less often than access tokens and stored by the client, they are a prime target for theft. If an attacker steals a refresh token, they can silently mint access tokens until the token expires or is revoked. Unlike access tokens, which are short-lived and validated by signature alone, refresh tokens require server-side state to be revocable. That state is exactly what Redis can provide—but only if it is designed correctly.

Core Principle: Hash the Token, Not the Raw Value

Storing the raw refresh token in Redis is dangerous. If Redis is compromised, all tokens leak. Instead, store a SHA-256 hash of the token. The hash is what you look up and compare. This way, even if an attacker dumps Redis, they get hashes that are impractical to reverse (assuming the token has enough entropy). Use a key like refresh:{sha256(token)} with a TTL matching the token’s lifetime.

  • Token generation: create a random value (e.g., 256 bits) and return it to the client.
  • Storage: store the SHA-256 hash in Redis with an expiration.
  • Validation: hash the presented token and look up that key.

Atomic Rotation: The Heart of Safe Revocation

The critical moment is when a refresh token is used. If you simply read the hash, then delete it, then issue a new token, a race condition can occur: two requests with the same token might both pass the read before either deletes. To prevent this, use a Lua script that atomically checks, deletes, and optionally stores a new token. Redis scripts run atomically, so no other command can interleave.

A minimal Lua script for rotation:

local old = KEYS[1]
local new = KEYS[2]
local ttl = ARGV[1]
if redis.call('GET', old) then
  redis.call('DEL', old)
  redis.call('SET', new, '1', 'EX', ttl)
  return 1
end
return 0

If the script returns 0, the token was already used or revoked—reject the request. If it returns 1, the rotation succeeded and the client receives a new refresh token. This guarantees that a replayed token can never be used twice, even under concurrent requests.

Choosing the Right Redis Data Type

For most cases, a simple string key with a TTL is sufficient. But consider these options:

  • String with TTL: simplest, good for one token per user per device. Use SET refresh:{hash} 1 EX {ttl}.
  • Hash: if you need to store metadata (e.g., user ID, device ID, expiration), use a hash keyed by token hash. But then TTL must be set on the whole hash, and rotation becomes more complex.
  • Set or Sorted Set: if a user can have multiple active refresh tokens (e.g., one per device), store a set of token hashes per user. To revoke all, delete the set. To revoke one, remove a member. TTL per member is not native—use a sorted set with expiration timestamps and clean up periodically.

Revocation Scenarios and How to Handle Them

There are several situations where you must revoke a refresh token:

  1. Logout: delete the token hash immediately. If the token is presented again, it will not be found.
  2. Password change: revoke all tokens for that user. If you store tokens per user in a set, delete the whole set.
  3. Admin force-logout: same as password change, but for a specific device or all devices.
  4. Token reuse detection: if a refresh attempt fails because the token is missing, that means it was already used or revoked. You should flag that as a potential replay and revoke the entire user’s session family.

Common Pitfalls and How to Avoid Them

Many implementations fail because of subtle mistakes:

  • Not hashing the token: storing raw tokens in Redis is a security risk if Redis is compromised.
  • No TTL on keys: tokens that never expire accumulate and become a liability. Always set a TTL matching the token’s intended lifetime.
  • Non-atomic rotation: using GET then DEL in application code leads to race conditions. Use Lua scripts or WATCH/MULTI/EXEC.
  • Ignoring replay after rotation: if a token is used twice, the second attempt should not just fail—it should trigger a security event and revoke all tokens for that user.
  • Using Redis as the only store: Redis is fast but volatile if not persisted. For critical revocation, consider writing events to a durable store as well, or enable Redis persistence (AOF) to reduce data loss.

Alternatives and When to Use Them

Redis is not the only way to revoke refresh tokens. Consider these alternatives:

  • Database table: store token hashes in a relational database with an index. Slower but durable. Good for low-throughput systems.
  • JWT with short expiry: if refresh tokens are JWTs, they cannot be revoked server-side without a denylist. You would still need Redis to store the jti (token ID) until expiry.
  • Token versioning: store a version number per user in Redis. Include the version in the refresh token as a claim. On refresh, compare the version; if it does not match, reject. This allows revoking all tokens by incrementing the version.

Frequently Asked Questions

Q: Can I just delete the Redis key on logout?
Yes, that is sufficient for that token. But if the user has multiple devices, you need to delete all keys for that user, which requires a pattern like refresh:{userid}:*. Be careful with KEYS in production—use SCAN instead.

Q: What if Redis goes down? Are tokens still revoked?
If Redis is down, you cannot check revocation. You should fail closed: reject refresh requests if Redis is unavailable, rather than allowing them. Alternatively, use Redis with high availability (sentinel or cluster) and persistence to minimize downtime.

Q: How do I handle token reuse detection?
When a refresh attempt fails because the token hash is not found, that could be a replay. Immediately revoke all tokens for that user by deleting all keys with that user’s prefix. Then force a re-login.

Q: Should I store the token ID (jti) instead of the hash?
Yes, that works too. If your refresh token is a JWT, you can store the jti in Redis. On refresh, extract the jti and check if it exists. This is simpler than hashing the whole token, but ensure the jti is unique and random.

Q: How long should the TTL be?
Set it equal to the refresh token’s lifetime. If your refresh token expires in 30 days, set TTL to 30 days. If you want to allow sliding expiration, you can reset the TTL on each refresh, but that means a token can live forever if used regularly—decide if that is acceptable.

Q: Is it safe to store the hash in Redis without encryption?
Yes, because the hash is not reversible. But ensure Redis is protected by a strong password and network isolation. Also, use TLS for Redis connections if possible.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →