Course contentsShow
← Security
Lesson 791 of 3,05216. Web Security - Authentication MechanismsFree lesson

JWT Expiration and Revocation

Managing token lifetime with exp and nbf claims; challenges of revoking stateless JWTs.

JWT Expiration and Revocation

You'll learn how to control JWT lifetimes and why revoking stateless tokens is surprisingly hard.

Controlling Token Lifetime

JWTs can include time-based claims to limit their validity window:

  • exp (expiration): A Unix timestamp after which the token is invalid. The server should reject any token where the current time exceeds exp.
  • nbf (not before): A Unix timestamp before which the token shouldn't be accepted yet. Useful for tokens issued ahead of time.

When validating, always check these claims:

// Pseudocode validation
if (currentTime >= token.exp) {
    throw "Token expired";
}
if (currentTime < token.nbf) {
    throw "Token not yet valid";
}

Why it matters: Short expiration times (minutes to hours) limit damage if a token is stolen. The attacker's window shrinks dramatically.

The Revocation Problem

Here's the catch: JWTs are stateless by design. The server doesn't store them or maintain a session database. It just validates the signature and checks claims. But what if you need to revoke a valid token immediately—like when a user logs out or changes their password?

You can't truly revoke a stateless JWT without adding state back in:

  • Maintain a blocklist of revoked token IDs (jti claim) until their exp passes
  • Store tokens in Redis or similar and check on every request (loses statelessness benefit)
  • Keep expiration times very short (5-15 minutes) and use refresh tokens for renewal

Analogy: It's like a movie ticket with a timestamp. Once printed with a valid signature, the theater accepts it—you can't remotely "cancel" that specific ticket unless they check a cancellation list at the door.

Key Takeaway: Use exp claims to limit JWT lifetime automatically, but accept that true revocation requires reintroducing server-side state—making short expiration times your best defense against compromise.