Revoking stateless JWTs immediately with Redis token versions
Revoke active stateless JWTs on logout-all or account deletion using per-user Redis token versions with O(1) memory and Spring Security validation.
Stateless JWTs scale without server-side session storage, but they leave an awkward gap: you can’t immediately invalidate an active access token on global logout or account deletion. This post explains how I solved that using per-user token versions in Redis with
O(1)memory per user and a two-stage Spring Security validator.
The problem: deleted accounts can still call APIs
The main reason teams pick JWT authentication is statelessness. The server verifies the cryptographic signature and exp claim on each request without hitting a session store.
That convenience turns into a security hole as soon as you hit three routine production scenarios:
- Lost device or suspected compromise: A user clicks “Log out of all devices.”
- Password change: Every existing session on other devices must stop working immediately.
- Account deletion or ban: A user deletes their account—or an admin bans them—and shouldn’t be able to make another API call.
Deleting refresh tokens from Redis or the database stops new access tokens from being minted. It does nothing to access tokens already sitting in a browser or mobile app with 15 to 30 minutes left before exp. Letting a deleted account read private data or post content for another 25 minutes is unacceptable for both security and data integrity.
Comparing revocation strategies
I evaluated three common ways to revoke stateless access tokens before expiry:
| Criteria | 1. Per-token JTI blacklist | 2. Per-user invalidatedAt timestamp | 3. Per-user Token Version (chosen) |
|---|---|---|---|
| Storage model | Store every revoked token’s jti in Redis | Store one logout timestamp per user | Store one active UUID (token_version) per user |
| Logout-all support | No (server doesn’t track all active JTIs) | Yes (iat < invalidatedAt) | Yes (overwrite with a new UUID) |
| Memory complexity | O(N) (grows with active revoked tokens) | O(1) (1 key per user) | O(1) (1 key per user, ~88 bytes) |
| Concurrency / clock issues | None | Clock skew and 1-second iat granularity races | None (exact string equality check) |
Why I skipped JTI blacklists and timestamps
- Per-token JTI blacklist: Works for single-device logout, but fails for “log out of all devices” unless you also track every issued access token on the server—defeating the point of stateless tokens and inflating Redis memory linearly with traffic.
- Invalidated timestamp (
iat < invalidatedAt): Looks simple until you remember RFC 7519 definesiatin whole seconds, not milliseconds. If a user logs out and refreshes—or logs back in—within the same second,iat == invalidatedAtcauses a race condition that either rejects a brand-new valid token or lets a revoked token slip through.
Why I chose per-user Token Version
Every JWT carries a token_version string claim. Redis stores a single key per user (token:version:{userId}) holding the current valid UUID.
When a user triggers logout-all, changes their password, or deletes their account, the server overwrites that Redis key with a new random UUID. On each request, Spring Security compares the JWT’s token_version claim against the Redis value. Any mismatch fails immediately with 401 Unauthorized—no timestamp math, no clock-skew bugs, and strictly one tiny key per user.
Architecture: TokenVersionStore and two-stage JWT validation
Here is the full validation path for an incoming API request:
sequenceDiagram
autonumber
actor Client as Client (App/Web)
participant Filter as JwtDecoder (Spring Security)
participant Redis as Redis (TokenVersionStore)
participant DB as UserRepository (RDB)
participant Controller as Business API
Client->>Filter: API request (Bearer AccessToken)
Note over Filter: Stage 1: Verify signature (HS256) and exp
alt Forged signature or expired
Filter-->>Client: 401 Unauthorized (AUTH-001 / AUTH-002)
else Valid signature
Filter->>Redis: GET token:version:{userId}
Redis-->>Filter: Current active version
alt token version != Redis currentVersion
Filter-->>Client: 401 Unauthorized (AUTH-008 REVOKED_TOKEN)
else Version matches
Filter->>DB: Check active account (existsById)
alt Account deleted
Filter-->>Client: 401 Unauthorized (AUTH-008 REVOKED_TOKEN)
else Active user
Filter->>Controller: Populate SecurityContext & handle request
Controller-->>Client: 200 OK
end
end
end
Implementing TokenVersionStore in Redis
The key invariant for TTL management is simple: a revocation marker must never expire before the tokens it invalidated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// src/main/kotlin/com/example/server/auth/application/TokenVersionStore.kt
package com.example.server.auth.application
import com.example.server.security.jwt.JwtProperties
import java.util.UUID
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component
/** Invalidates active and in-flight tokens under the same user version key. */
@Component
class TokenVersionStore(
private val redis: StringRedisTemplate,
properties: JwtProperties,
) {
// Use the longer of refresh/access TTL plus clock skew so the marker outlives all tokens
private val ttl = maxOf(properties.refreshTokenTtl, properties.accessTokenTtl) + properties.clockSkew
fun current(userId: String): String = redis.opsForValue().get(key(userId)) ?: ""
/**
* Atomically reads the current version and extends its TTL (Redis GETEX)
* so the revocation marker never expires ahead of a newly issued token.
*/
fun forIssue(userId: String): String = redis.opsForValue().getAndExpire(key(userId), ttl) ?: ""
/**
* Overwrites the user's version with a fresh UUID on logout-all or withdrawal.
*/
fun revoke(userId: String) {
redis.opsForValue().set(key(userId), UUID.randomUUID().toString(), ttl)
}
private fun key(userId: String): String = "token:version:$userId"
}
forIssue(userId)uses RedisGETEX(getAndExpire) to read the version and refresh its TTL in one atomic operation whenever a new token is minted. Active users never lose their version key mid-session.revoke(userId)writes a fresh UUID with the maximum token TTL. Every previously issued access and refresh token becomes stale immediately.
Implementation: wiring into Spring Security and domain services
1. Custom OAuth2TokenValidator in JwtConfig
In Spring Security, I attach a custom ActiveTokenValidator to NimbusJwtDecoder so version checks run right after standard cryptographic validation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// src/main/kotlin/com/example/server/security/jwt/JwtConfig.kt
package com.example.server.security.jwt
import com.example.server.auth.application.TokenVersionStore
import com.example.server.user.domain.UserRepository
import java.util.UUID
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator
import org.springframework.security.oauth2.core.OAuth2Error
import org.springframework.security.oauth2.core.OAuth2ErrorCodes
import org.springframework.security.oauth2.core.OAuth2TokenValidator
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder
@Configuration
class JwtConfig(
private val properties: JwtProperties,
private val tokenVersions: TokenVersionStore,
private val userRepository: UserRepository,
) {
@Bean
fun jwtDecoder(): JwtDecoder {
val decoder = NimbusJwtDecoder.withSecretKey(secretKey).build()
// Stage 1: CPU-only signature, expiry, issuer, and token type checks
val standardValidators = DelegatingOAuth2TokenValidator(
ExpiryValidator(properties),
JwtTimestampValidator(properties.clockSkew),
JwtIssuerValidator(properties.issuer),
JwtClaimValidator<String>(JwtProvider.TOKEN_TYPE_CLAIM) { it == JwtProvider.ACCESS_TOKEN_TYPE },
)
// Stage 2: Redis token version and active account lookup
val activeTokens = ActiveTokenValidator(tokenVersions, userRepository)
decoder.setJwtValidator { token ->
val result = standardValidators.validate(token)
// Only hit Redis/DB after cryptographic and expiry checks pass
if (result.hasErrors()) result else activeTokens.validate(token)
}
return decoder
}
/** Validates token version equality and active user state without timestamp races. */
private class ActiveTokenValidator(
private val versions: TokenVersionStore,
private val users: UserRepository,
) : OAuth2TokenValidator<Jwt> {
override fun validate(token: Jwt): OAuth2TokenValidatorResult {
val userId = runCatching { UUID.fromString(token.subject) }.getOrNull()
?: return OAuth2TokenValidatorResult.failure(
OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, "Missing or invalid sub claim.", null)
)
val version = token.getClaimAsString(JwtProvider.TOKEN_VERSION_CLAIM) ?: ""
// Reject immediately if version mismatches Redis or the account is soft-deleted
if (version != versions.current(userId.toString()) || !users.existsById(userId)) {
return OAuth2TokenValidatorResult.failure(
OAuth2Error(REVOKED_ERROR_CODE, "Token has been revoked.", null)
)
}
return OAuth2TokenValidatorResult.success()
}
}
companion object {
const val REVOKED_ERROR_CODE = "token_revoked"
}
}
2. Triggering revocation on logout-all and account deletion
Both global logout and account withdrawal call the same TokenService.revokeAll(userId) method (which also powers theft detection in my Refresh Token Rotation setup).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/kotlin/com/example/server/auth/application/TokenService.kt
@Service
class TokenService(
private val refreshTokenRepository: RefreshTokenRepository,
private val tokenVersions: TokenVersionStore,
) {
/**
* Revokes every active session for the user:
* 1. Bumps the Redis token version to a new UUID -> invalidates all access tokens.
* 2. Deletes all stored refresh tokens for the user.
*/
fun revokeAll(userId: String) {
tokenVersions.revoke(userId)
refreshTokenRepository.deleteAll(refreshTokenRepository.findAllByUserId(userId))
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/main/kotlin/com/example/server/user/application/UserService.kt
@Service
class UserService(
private val userRepository: UserRepository,
private val tokenService: TokenService,
) {
/**
* Soft-deletes the user and revokes all active tokens immediately.
*/
@Transactional
fun withdraw(userId: UUID) {
findUser(userId).delete()
tokenService.revokeAll(userId.toString())
}
}
Controlling Redis overhead on every request
A fair pushback here is: “If you query Redis on every authenticated request, aren’t you giving up the whole zero-I/O benefit of stateless JWTs?”
You are trading pure zero-I/O verification for immediate revocation, so you want to keep that I/O cheap and bounded:
- Verify signatures before touching Redis: Notice how
jwtDecoder()short-circuits whenstandardValidators.validate(token)returns errors. Forged, malformed, or expired junk tokens get rejected in CPU memory and never reach Redis, blocking unauthenticated traffic from turning into a Redis DoS vector. - Single-key
O(1)GET: Lookups hit one exact string key (token:version:{userId}) with no set scans or pattern matching. On a local or VPC Redis instance, a singleGETtakes under 0.3 ms. - Optional short-TTL Caffeine L1 cache: If you handle tens of thousands of requests per second per user, put a 1–3 second Caffeine + Redis two-tier cache in front of
TokenVersionStore. Accepting a 1–3 second revocation window cuts repeat Redis calls by over 95%.
When not to use this pattern: If your access token TTL is already very short (1–2 minutes) and you don’t have strict immediate-revocation compliance rules, pure stateless JWT verification is simpler and removes Redis from the hot path. Also, if your Redis instance is evicted or restarted without persistence, every user’s
token:versionkey disappears (returning""), which forces clients with non-empty version claims to re-authenticate—plan for AOF persistence or a fallback policy before enabling it.
Verification
I verified the flow end-to-end against the running API and inspected Redis directly.
1. Calling logout-all (POST /api/v1/auth/logout-all)
With active sessions open on desktop and mobile, I called the global logout endpoint:
1
2
curl -X POST https://api.namju.kim/api/v1/auth/logout-all \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI..."
Figure 1. POST /api/v1/auth/logout-all returning 200 OK after rotating the user’s token version.
2. Reusing an unexpired access token
Next, I called GET /api/v1/users/me with an access token issued before logout that still had 28 minutes left before exp:
1
2
curl -X GET https://api.namju.kim/api/v1/users/me \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI..."
Figure 2. ActiveTokenValidator blocking the unexpired token with 401 Unauthorized (AUTH-008).
Even though the HMAC signature and exp were still valid, ActiveTokenValidator caught the version mismatch and blocked the request with 401 Unauthorized (AUTH-008).
3. Inspecting Redis state and memory footprint
Checking the key in redis-cli confirmed the version UUID, TTL, and memory footprint:
Figure 3. Redis key inspection showing the UUID value, ~14-day TTL, and 88-byte memory footprint.
token:version:{userId}stores the newly generated UUID.- Its TTL matches the maximum refresh token lifetime (~14 days), so inactive keys clean themselves up without a background cleanup job.
- Memory usage is roughly 88 bytes per user, keeping the footprint small even at large user counts.
Summary checklist
- Use token versions over timestamps: Comparing a UUID claim against one Redis key avoids
O(N)JTI blacklists and 1-secondiatrace conditions. - Extend TTL atomically with
GETEX: Refresh the version key’s TTL whenever issuing a new token so active revocation markers never expire early. - Keep Redis behind signature verification: Run cryptographic and
expchecks first so invalid traffic never reaches Redis. - Pair with account-state checks: Check
existsById(or a cached user status) alongside the version so soft-deleted accounts are blocked immediately.