Skip to content
Blog

← All articles

What the jti Claim Is Actually For: JWT Replay Protection and Revocation

The jti (JWT ID) claim does nothing on its own. How to use it to stop replayed tokens and revoke tokens early: an atomic Redis replay store that accepted 1 of 50 concurrent copies where check-then-set accepted all 50, why you must verify before you remember, which tokens should be single-use, how unique a jti must be, and a denylist that cleans itself up. Tested with jose, Redis 8.2, and PostgreSQL 18.

By 25 min read

Every JWT tutorial lists jti among the registered claims, and most say it “prevents replay attacks”. It doesn’t, on its own. A jti is just a unique name for one token. Replay protection, revocation, and audit trails are things you build on top of it, and each one is easy to get subtly wrong.

This article builds them: a replay store that accepts each token exactly once across any number of servers, a denylist that revokes a token before it expires and then cleans up after itself, and the checks around them. Along the way, we race 50 servers against the same token, burn a real token with a forged one, and measure how much each stored ID costs. Every example was run before publishing, with jose on Node.js 24 against Redis 8.2 and PostgreSQL 18.

The short answer#

What jti is, and where it’s required#

RFC 7519 defines jti in one paragraph. It’s a case-sensitive string that uniquely identifies the token, assigned so that the chance of two tokens getting the same value is negligible, including across issuers if there are several. The RFC says it “can be used to prevent the JWT from being replayed”, and makes it optional.

Several later standards make it required, and say what it’s for:

TokenjtiWhat it’s for
Any JWT (RFC 7519)OptionalWhatever the application needs
JWT access token (RFC 9068)RequiredIdentifying the token: logs, revocation
Client assertion (RFC 7523, OpenID Connect private_key_jwt)Optional in RFC 7523, required by OpenID ConnectRefusing a second use
DPoP proof (RFC 9449)RequiredRefusing a second use for the same URI
Logout token (OpenID Connect Back-Channel Logout)RequiredDetecting a replayed logout
Security Event Token (RFC 8417)RequiredProcessing each event once

Notice what no library does: remember the values it has seen. jose will reject a token whose jti is missing if you list it in requiredClaims, but it doesn’t check that the value is a usable ID:

jti-type.mjs
// jti-type.mjs: jose checks that a required jti is present, not that it's a usable ID.
import { SignJWT, jwtVerify } from "jose";

const key = crypto.getRandomValues(new Uint8Array(32)); // HS256, to keep the example short
const sign = (claims) => new SignJWT(claims).setProtectedHeader({ alg: "HS256" }).setExpirationTime("5m").sign(key);

for (const jti of [123, "", { id: 1 }]) {
  const { payload } = await jwtVerify(await sign({ jti }), key, { requiredClaims: ["jti", "exp"] });
  console.log("accepted", JSON.stringify(payload.jti)); // all three are accepted
}

// RFC 7519 says a jti is a case-sensitive string. Check that yourself, and cap the length before
// storing it (RFC 9449, section 11.1, warns about memory exhaustion through huge jti values).
function assertJti(payload) {
  if (typeof payload.jti !== "string" || payload.jti.length === 0 || payload.jti.length > 256) {
    throw new Error("invalid jti");
  }
  return payload.jti;
}
try { assertJti({ jti: 123 }); } catch (e) { console.log(e.message); } // invalid jti

A number, an empty string, and an object all pass. PyJWT 2.15 is stricter: it rejects a non-string jti with InvalidJTIError, but still accepts an empty string. Either way, if you’re going to use the value as a key, check it yourself.

Single use or identity: which tokens to check#

Before building a replay store, decide which tokens go through it. The most common mistake with jti is treating every token as single-use.

A bearer access token is meant to be replayed. The client sends the same token on every request until it expires; that’s the whole design. Put access tokens through a “first use only” check and the second API call fails. For them, the jti is an identity: something to log, to correlate requests by, and to revoke. If replaying a stolen access token is the threat, the answers are short lifetimes (see short-lived access tokens) and sender-constrained tokens like DPoP, not a replay check.

One-time tokens should be checked. A client assertion authenticates a single request to the token endpoint; a DPoP proof covers a single HTTP request; a logout token announces a single event. Each is valid for a minute or so, and anyone who captures one during that time can send it again. That’s what the replay store is for.

Making a good jti#

Use crypto.randomUUID() (or your platform’s equivalent). A version 4 UUID has 122 random bits from a cryptographically secure generator, so collisions are not a practical concern. If the IDs end up in a database index, as they do in the PostgreSQL store below, a time-ordered v7 UUID is kinder to the index and still has 74 random bits per millisecond (see UUID v4 vs. v7). A v7 UUID reveals when it was made, but so does the token’s iat.

Don’t shorten it. A collision isn’t just untidy: with a replay store, the second token with the same ID is rejected as a replay, and with a denylist, revoking one token revokes another. How soon does that happen?

collisions.mjs
// collisions.mjs: how many random IDs until there's a 50% chance that two are equal?
// The birthday bound: √(2 ln 2 × N), about 1.18 × √N, where N is the number of possible values.
const half = (bits) => Math.sqrt(2 * Math.LN2 * 2 ** bits);

console.log(Math.round(half(32)).toLocaleString("en-US")); // 77,163    8 hex characters
console.log(half(64).toExponential(1));                     // 5.1e+9   16 hex characters
console.log(half(122).toExponential(1));                    // 2.7e+18  a UUID v4 (122 random bits)

// The same thing by experiment: shorten a UUID to 8 characters and count until the first repeat.
const seen = new Set();
let n = 0;
for (let id; !seen.has((id = crypto.randomUUID().slice(0, 8))); n++) seen.add(id);
console.log(n); // different every run, around 80,000 on average

Eight hex characters, a tempting “short ID”, give a coin-flip chance of a repeat after about 77,000 tokens. Over 300 runs of the experiment, the first repeat came after about 82,000 tokens on average, just as theory predicts. A busy service issues that many in minutes. A full UUID needs about 2.7 × 1018. Encoding the UUID more compactly, as Base62 or Base64url, keeps all 122 bits; cutting characters off doesn’t (the short UUID article has the math, and the collision calculator does it for any length).

Don’t use a counter. Sequential IDs collide as soon as you run two issuers, or restart one without its state. They’re also predictable, which matters in the next section but one: anyone who can guess the next jti can try to use it up first.

Scope it by issuer. RFC 7519 asks for uniqueness across issuers, but you only control your own. If a verifier accepts tokens from several issuers (tenants, partner clients, the clients that sign DPoP proofs), store the pair (iss, jti), not the jti alone. Otherwise, one issuer can send tokens with another issuer’s IDs and get that issuer’s real tokens rejected.

A replay store that works on every server#

An in-memory set works for one process; the private key JWT article uses one. Behind a load balancer, each instance has its own set, so a captured token can be replayed once per instance. The store has to be shared, and the check has to be atomic. In Redis, that’s a single command: SET key 1 NX EXAT expiry, which sets the key only if it doesn’t exist, with an absolute expiry time, and says whether it did.

replay-redis.mjs
// replay-redis.mjs: accept each (issuer, jti) once, across every server, with one atomic Redis command.
import { createHash } from "node:crypto";
import { SignJWT, jwtVerify, generateKeyPair } from "jose";
import Redis from "ioredis";

const LEEWAY = 30; // seconds of clock skew jwtVerify allows: a token is accepted until exp + 30

// True the first time this issuer's jti is seen, false after that. The key deletes itself at keepUntil
// (Unix seconds), the moment the token could no longer be accepted anyway.
export async function firstUse(redis, iss, jti, keepUntil) {
  // Hashed: a fixed-size key whatever the jti's length, and scoped by issuer.
  const id = createHash("sha256").update(JSON.stringify([iss, jti])).digest("base64url");
  return (await redis.set(`jti:${id}`, "1", "EXAT", keepUntil, "NX")) === "OK";
}

export async function acceptOnce(redis, token, publicKey) {
  // 1. Verify first: signature, issuer, audience, expiry.
  const { payload } = await jwtVerify(token, publicKey, {
    algorithms: ["ES256"],
    issuer: "https://client.example",
    audience: "https://api.example",
    requiredClaims: ["jti", "exp"],
    clockTolerance: LEEWAY,
  });
  if (typeof payload.jti !== "string" || !payload.jti || payload.jti.length > 256) throw new Error("invalid jti");
  // 2. Then remember it, until exp + LEEWAY.
  if (!(await firstUse(redis, payload.iss, payload.jti, payload.exp + LEEWAY))) throw new Error("replayed jti");
  return payload;
}

if (import.meta.main) {
  const redis = new Redis(process.env.REDIS_URL);
  const { publicKey, privateKey } = await generateKeyPair("ES256");
  const token = await new SignJWT({})
    .setProtectedHeader({ alg: "ES256" })
    .setIssuer("https://client.example")
    .setAudience("https://api.example")
    .setJti(crypto.randomUUID())
    .setIssuedAt()
    .setExpirationTime("60s")
    .sign(privateKey);

  console.log("first use:", (await acceptOnce(redis, token, publicKey)).jti);
  await acceptOnce(redis, token, publicKey).catch((e) => console.log("second use:", e.message)); // replayed jti
  const [key] = await redis.keys("jti:*");
  console.log("forgotten in", await redis.ttl(key), "seconds"); // about 90: the 60 s lifetime plus the leeway
  redis.disconnect();
}

How long to remember. An entry has to outlast every moment when the token could still be accepted. With clockTolerance: 30, jose accepts a token up to 30 seconds after its exp (we checked: accepted at 20 seconds past, rejected at 31). An entry that expired exactly at exp would let the token be replayed during those 30 seconds, so the key lives until exp + LEEWAY. After that, the token fails the expiry check on its own, and Redis deletes the key. Nothing needs cleaning up.

Require exp. jose accepts a token with no exp at all unless requiredClaims includes it. A one-time token that never expires would require its ID to be remembered forever.

Why one command matters. The obvious version, “does the key exist? If not, set it”, takes two round trips, and other servers can act in between. Here are 50 servers, each with its own connection, receiving the same token at the same moment:

race.mjs
// race.mjs: 50 servers receive the same token at the same moment. How many accept it?
import Redis from "ioredis";
import { firstUse } from "./replay-redis.mjs";

const servers = Array.from({ length: 50 }, () => new Redis(process.env.REDIS_URL)); // a connection each
await Promise.all(servers.map((r) => r.ping()));
const keepUntil = Math.floor(Date.now() / 1000) + 90;

// Check, then set: two round trips with a gap between them.
async function checkThenSet(redis, iss, jti, keepUntil) {
  const key = `naive:${iss}:${jti}`;
  if (await redis.exists(key)) return false;
  await redis.set(key, "1", "EXAT", keepUntil);
  return true;
}

for (const [name, use] of [["check, then set", checkThenSet], ["SET NX", firstUse]]) {
  const jti = crypto.randomUUID();
  const results = await Promise.all(servers.map((r) => use(r, "https://client.example", jti, keepUntil)));
  console.log(`${name}: ${results.filter(Boolean).length} of 50 accepted`);
}
servers.forEach((r) => r.disconnect());

In ten runs, check-then-set accepted the token on all 50 servers every time. Every server’s check ran before any server’s set. SET NX accepted it exactly once in every run. A replayed token rarely arrives 50 times in the same millisecond, but an attacker can arrange two, and the window is real. (The same lesson in a different setting: rate limiting inside Redis measured GET-then-SET letting through 17 times the limit.)

Verify first, then remember#

The replay store is only for tokens that have passed every other check. Record a jti before checking the signature, and anyone can use up a real token’s ID with a forged one:

order.mjs
// order.mjs: what happens if the jti is recorded before the signature is checked.
import { SignJWT, jwtVerify, generateKeyPair, decodeJwt } from "jose";

const used = new Set(); // stands in for the replay store
const issuer = await generateKeyPair("ES256");
const attacker = await generateKeyPair("ES256");
const sign = (key, jti) =>
  new SignJWT({}).setProtectedHeader({ alg: "ES256" }).setJti(jti).setExpirationTime("60s").sign(key);

const jti = crypto.randomUUID();
const real = await sign(issuer.privateKey, jti);
const forged = await sign(attacker.privateKey, jti); // the same jti, signed with the wrong key

async function rememberThenVerify(token) {
  const { jti } = decodeJwt(token); // not verified yet!
  if (used.has(jti)) return "rejected (replay)";
  used.add(jti);
  return jwtVerify(token, issuer.publicKey).then(() => "accepted", () => "rejected (signature)");
}

async function verifyThenRemember(token) {
  const verified = await jwtVerify(token, issuer.publicKey).catch(() => null);
  if (!verified) return "rejected (signature)";
  if (used.has(verified.payload.jti)) return "rejected (replay)";
  used.add(verified.payload.jti);
  return "accepted";
}

for (const check of [rememberThenVerify, verifyThenRemember]) {
  used.clear();
  // The forged token arrives first, then the real one.
  console.log(`${check.name}: forged ${await check(forged)}, real ${await check(real)}`);
}

The output:

rememberThenVerify: forged rejected (signature), real rejected (replay)
verifyThenRemember: forged rejected (signature), real accepted

In the first version, the forged token fails its signature check but leaves its jti behind, and the real token is turned away as a replay. The attacker needs only the ID, which is readable in any token they’ve seen and guessable if IDs are sequential. Unverified tokens can also fill the store with junk. Verify the signature, issuer, audience, and expiry, then remember the jti.

The same goes for keying on the token string: an ES256 token can be re-spelled into a different string that still verifies (the twin tokens in the JWS article), so a store keyed on the string or its hash lets each twin through once. Key on the verified jti.

The same store in PostgreSQL#

If you already have PostgreSQL and not Redis, a table with a primary key does the same job. The insert either adds the row or does nothing, atomically:

replay.sql
-- replay.sql: the replay store as a table. The primary key does the "only once".
CREATE TABLE used_jti (
  iss        text        NOT NULL,
  jti        text        NOT NULL,
  expires_at timestamptz NOT NULL,
  PRIMARY KEY (iss, jti)
);
CREATE INDEX ON used_jti (expires_at); -- for the clean-up job
replay-pg.mjs
// replay-pg.mjs: the same first-use check in PostgreSQL. INSERT ... ON CONFLICT DO NOTHING is atomic.
import pg from "pg";

export async function firstUse(db, iss, jti, keepUntil) {
  const { rowCount } = await db.query(
    "INSERT INTO used_jti (iss, jti, expires_at) VALUES ($1, $2, to_timestamp($3)) ON CONFLICT DO NOTHING",
    [iss, jti, keepUntil],
  );
  return rowCount === 1; // 0 rows: someone inserted it first
}

// Run every minute or so. Rows past expires_at belong to tokens that fail the exp check anyway.
export const sweep = (db) => db.query("DELETE FROM used_jti WHERE expires_at < now()");

if (import.meta.main) {
  const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 50 });
  const jti = crypto.randomUUID();
  const keepUntil = Math.floor(Date.now() / 1000) + 90;
  const results = await Promise.all(
    Array.from({ length: 50 }, () => firstUse(db, "https://client.example", jti, keepUntil)),
  );
  console.log(`${results.filter(Boolean).length} of 50 accepted`); // 1 of 50 accepted
  await db.end();
}

Fifty concurrent inserts of the same ID, through a pool of 50 connections: one accepted, in each of ten runs. The primary key on (iss, jti) scopes it by issuer. Unlike Redis, the rows don’t expire by themselves, so a job calls sweep every minute or so. Leftover rows are harmless in the meantime: they belong to tokens that fail the expiry check anyway.

How big does the store get?#

Because each entry lives only as long as its token, the store holds roughly tokens per second × (lifetime + leeway) entries, however long the service runs. We measured 100,000 keys, each shaped like the ones above, in Redis 8.2: 116 bytes each, including the expiry.

So a token endpoint taking 1,000 client assertions a second, each valid for 60 seconds with 30 seconds of leeway, holds about 90,000 entries: around 10 MB. Most services are far below that. The number to watch is the lifetime: a one-time token valid for an hour needs 60 times the memory of one valid for a minute, for no benefit.

Revoking a token before it expires#

Access tokens are verified without asking the issuer, which is the point of JWTs, and also why they can’t simply be canceled. When a user logs out, changes their password, or an account is suspended, the outstanding access tokens stay valid until they expire. Short lifetimes keep that window small. When it must be closed now, a denylist does it:

revoke.mjs
// revoke.mjs: revoking access tokens before they expire, with a denylist keyed on the jti
// and a per-user cutoff for "log out everywhere".
import { createHash } from "node:crypto";
import { SignJWT, jwtVerify, generateKeyPair, decodeJwt } from "jose";
import Redis from "ioredis";

const ISSUER = "https://auth.example";
const LIFETIME = 15 * 60; // the longest access-token lifetime, in seconds
const LEEWAY = 30;
const redis = new Redis(process.env.REDIS_URL);
const { publicKey, privateKey } = await generateKeyPair("ES256");
const keyFor = (p) => "revoked:" + createHash("sha256").update(JSON.stringify([p.iss, p.jti])).digest("base64url");

// Revoke one token: remember its jti until the token would have expired anyway.
const revoke = (payload) => redis.set(keyFor(payload), "1", "EXAT", payload.exp + LEEWAY);

// Revoke every token a user holds right now: anything issued at or before this second.
const revokeAllFor = (sub) => redis.set(`cutoff:${sub}`, Math.floor(Date.now() / 1000), "EX", LIFETIME + LEEWAY);

async function check(token) {
  const { payload } = await jwtVerify(token, publicKey, {
    algorithms: ["ES256"],
    issuer: ISSUER,
    requiredClaims: ["jti", "exp", "iat", "sub"],
    clockTolerance: LEEWAY,
  });
  const [revoked, cutoff] = await Promise.all([redis.exists(keyFor(payload)), redis.get(`cutoff:${payload.sub}`)]);
  if (revoked) return "revoked";
  if (cutoff && payload.iat <= Number(cutoff)) return "revoked (logged out everywhere)";
  return "valid";
}

const issue = (sub) =>
  new SignJWT({}).setProtectedHeader({ alg: "ES256" }).setIssuer(ISSUER).setSubject(sub)
    .setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime(`${LIFETIME}s`).sign(privateKey);

const phone = await issue("user-7");
const laptop = await issue("user-7");
console.log(await check(phone), "/", await check(laptop)); // valid / valid

await revoke(decodeJwt(phone)); // we issued it, so its claims can be trusted here
console.log(await check(phone), "/", await check(laptop)); // revoked / valid
console.log("denylist entry expires in", await redis.ttl(keyFor(decodeJwt(phone))), "seconds"); // about 930

await revokeAllFor("user-7");
console.log(await check(laptop)); // revoked (logged out everywhere)
await new Promise((r) => setTimeout(r, 1100)); // iat has one-second resolution
console.log(await check(await issue("user-7"))); // valid: issued after the cutoff
redis.disconnect();

A denylist keyed on jti revokes one token, such as the session on a lost phone, and leaves the user’s other sessions alone. Like the replay store, each entry expires when its token would have, so the list holds only revoked tokens that are still unexpired: usually a handful.

A per-user cutoff handles “log out everywhere”: any token for that user issued at or before the cutoff is rejected. It needs no list of the user’s tokens, and it expires after the longest token lifetime. One catch: iat is in whole seconds, so a token issued in the same second as the logout is also rejected. That’s why the example waits a second before issuing the new token; in practice the user signs in again and it works.

Every API has to check. A denylist works only where it’s consulted, which costs each request a lookup in a shared store, the round trip JWTs were meant to avoid. Keep it to the services where an immediate logout matters, or push revocations to each instance and check them in memory. For refresh tokens, which are always checked at the authorization server, revocation is just deleting a row; that’s why the usual design pairs 5- to 15-minute access tokens with revocable refresh tokens.

Log the jti, never the token. A logged access token can be replayed by anyone who reads the logs, until it expires. The jti identifies the same token, correlates requests across services, and is what you’d put in the denylist. (More in JWS vs. JWE.)

Pitfalls#

  • Remembering before verifying. A forged token burns the real one’s ID. Verify everything, then record.
  • Check-then-set. Two round trips let concurrent copies through: 50 of 50 in our test. Use SET NX, a unique constraint, or a transaction that does both.
  • A store per instance. Behind a load balancer, a token can be replayed once per instance.
  • Single-use checks on access tokens. The second request fails. Access-token IDs are for revocation and logs.
  • Forgetting too early, or never. Keep entries until exp plus leeway. Require exp, or the store has to keep IDs forever.
  • Not scoping by issuer. With several issuers, one can block another’s tokens by reusing its IDs.
  • Short, sequential, or predictable IDs. They collide (eight hex characters: about 77,000 tokens for even odds), or can be guessed and used up first.
  • Trusting the library to validate it. jose accepts a numeric, empty, or object jti. Check the type and cap the length.
  • Keying on the token string. Twin tokens get through. Key on the verified (iss, jti).
  • Treating jti as a secret. Anyone holding the token can read it. It names the token; it doesn’t protect it.

FAQ#

Does adding a jti make a JWT single-use?

No. It gives the token a name. Single use comes from a server remembering the names it has seen, as in the replay store above.

Do I need a replay check if the token expires in a minute?

For one-time tokens, yes. A minute is plenty of time to replay a captured client assertion or DPoP proof, and OpenID Connect requires that a client assertion be refused on second use. The store costs little because entries live only that minute. (See private key JWT.)

Who chooses the jti?

Whoever signs the token chooses it. For access tokens that’s your authorization server; for client assertions and DPoP proofs it’s the client. That’s why the store is keyed by issuer and caps the length: a client can only collide with its own IDs, and can’t make you store megabytes.

Is a jti denylist the same as a session store?

No. A session store holds every live session, and every request looks one up. A denylist holds only revoked, unexpired tokens, usually very few. If every token had to be looked up anyway, an opaque token would be simpler than a JWT.

UUID v4 or v7?

Either is unique enough. Use v7 if the IDs go into a database index, v4 otherwise. Both are 36 characters, or 22 in Base62 with nothing lost.

How do I see a token’s jti?

Paste it into our JWT decoder. It shows every claim, converts iat and exp to dates, and verifies the signature, all in your browser. To generate IDs, use the UUID generator.

Get the code

  • jwt-dpop-sample on GitHub: jti used three ways in an ASP.NET Core and Angular app: single-use DPoP proofs, revoking access tokens at logout, and catching reused refresh tokens.

Try it in your browser