A refresh token is the most valuable credential an OAuth client holds: it keeps producing access tokens for days or weeks, with every scope the user consented to. Browser and mobile apps can't protect it with a client secret, so if it leaks, the thief can use it exactly as the app does. The OAuth 2.0 Security Best Current Practice, published in January 2025 as RFC 9700, gives authorization servers two ways to deal with that. One of them, refresh token rotation, needs nothing from the client but a little discipline, and it is what most identity providers offer.
This article reads what RFC 9700 actually requires, then builds the server side: a token endpoint that speaks RFC 6749 on the wire, binds tokens to their client and scope, and rotates them. Most of the design work turns out to be one question the RFC leaves open: what to do when a spent token comes back seconds later, from a race or a retry rather than a thief. We implemented three answers and tested each against four scenarios. For the surrounding design (token lifetimes, storage in the browser, logout), see our access and refresh tokens article. Everything here ran on PostgreSQL 18 with the jose library on Node.js 24.
The short answer#
What RFC 9700 requires#
Section 4.14 of RFC 9700 covers refresh tokens. It builds on RFC 6749, which already requires that refresh tokens be kept confidential, sent only over TLS, impossible to guess, and usable only by the client they were issued to. The additions:
| Requirement | Level | In the code below |
|---|---|---|
| Decide, based on a risk assessment, whether to issue refresh tokens to a client at all | MUST | A policy decision, outside the endpoint |
| Bind refresh tokens to the consented scope and resource servers | MUST | The grant stores the scope; a refresh can narrow it, never widen it |
| For public clients, detect replay: sender-constrained tokens or rotation | MUST | Rotation, with the grant revoked on reuse |
| If the grant is encoded in the token itself, protect its integrity (for example, sign it) | MUST | Not needed: tokens are random and the grant lives in the database |
| Expire refresh tokens after a period of client inactivity | SHOULD | 14-day idle limit per token, 90-day absolute limit per grant |
| Revoke refresh tokens on security events, such as a password change or logout | MAY | Set revoked_at on the grant |
| Confidential clients: tokens usable only by the client they were issued to (RFC 6749) | MUST | client_id checked on every refresh |
For confidential clients, the ones that authenticate with a secret or a private key, rotation is optional: a stolen refresh token is useless without the client's credentials. Rotation is the answer for the clients that have no credentials to steal alongside it.
How rotation detects a stolen token#
Without rotation, a refresh token is a bearer credential that works for weeks, and two copies of it are indistinguishable. With rotation, each token works once. Suppose an attacker copies the user's current token. From then on, both parties hold the same token, and only the first of them to use it gets a successor. Whoever uses it second presents a spent token, and that is the signal:
RFC 9700 is explicit that the server can't know which of the two is legitimate, so it revokes the active refresh token, at the cost of making the real user sign in again. That is why the server must retain the relationship between tokens: revoking "the grant" only works if every token issued from it can be found.
The refresh request on the wire#
The refresh is defined by RFC 6749, section 6: a form-encoded POST to the token endpoint with grant_type=refresh_token. A public client sends its client_id instead of authenticating and may send a scope to ask for less than the original grant.
# A public client (no secret) exchanging its refresh token, as RFC 6749 section 6 defines it.
curl -s https://auth.example.com/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d grant_type=refresh_token \
-d client_id=spa \
-d refresh_token=Hn2F0b9xXw3q7c8s5L4mQe1aT6yVvZ0jR2kP8uNdGc4A successful response carries a new access token and, with rotation, a new refresh token. The response must have Cache-Control: no-store so no proxy or browser cache keeps a copy.
{
"access_token": "eyJ0eXAiOiJhdCtqd3QiLCJhbGciOiJFUzI1NiJ9...",
"token_type": "Bearer",
"expires_in": 600,
"refresh_token": "q9Wc3n0YtB6aK1sXe8LfR2mZp5HdJ7vU4gTiNoQyE0w",
"scope": "orders:read orders:write profile"
}Failures are a JSON body with an error code. The ones that matter here are invalid_grant (the refresh token is unknown, expired, revoked, already used, or belongs to another client), invalid_scope (more scope than was granted), invalid_client (an unknown client, with status 401), and invalid_request or unsupported_grant_type for a malformed request. A client should treat invalid_grant as final: the session is over.
A token endpoint with rotation#
The data model has two tables. A grant is what the user consented to: a user, a client, a scope, and an absolute lifetime. Each refresh token belongs to a grant and is stored only as a SHA-256 hash. (Plain SHA-256 is enough for 256 random bits; our password vs. integrity hashing article explains why.)
-- schema.sql: one row per grant (what the user consented to, for which client), one row per refresh token ever
-- issued for it. Spent tokens stay until the grant ends: they are how a replay is recognized.
CREATE TABLE grants (
id uuid PRIMARY KEY DEFAULT uuidv7(),
user_id bigint NOT NULL,
client_id text NOT NULL, -- the client the tokens are bound to
scope text NOT NULL, -- what the user consented to: a refresh may narrow it, never widen it
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, -- absolute lifetime of the grant
revoked_at timestamptz,
revoked_why text
);
CREATE TABLE refresh_tokens (
hash bytea PRIMARY KEY CHECK (octet_length(hash) = 32), -- SHA-256 of the token, never the token
grant_id uuid NOT NULL REFERENCES grants ON DELETE CASCADE,
issued_at timestamptz NOT NULL DEFAULT now(),
idle_expires_at timestamptz NOT NULL, -- RFC 9700: expire refresh tokens after a period of inactivity
rotated_at timestamptz -- when it was first exchanged; from then on it is spent
);
CREATE INDEX ON refresh_tokens (grant_id);The endpoint handles the refresh_token grant. The authorization code grant would call startGrant once the user has signed in and consented.
// token-endpoint.mjs: the refresh_token grant of an OAuth 2.0 token endpoint, with refresh token rotation.
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { SignJWT } from "jose";
const ACCESS_TTL = 600; // seconds
const IDLE = "14 days"; // a refresh token unused this long expires
const ABSOLUTE = "90 days"; // and the whole grant ends after this, however active
const sha256 = (token) => createHash("sha256").update(token).digest();
const newRefreshToken = () => randomBytes(32).toString("base64url");
const error = (status, code) => ({ status, body: { error: code } });
// policy decides what happens when a spent refresh token comes back within `window` of its rotation:
// "strict" treat it as theft, like any other reuse: revoke the grant
// "refuse" reject it, but don't revoke (a race or a retry, not a theft)
// "reuse-window" exchange it again: the client gets another new refresh token
// Outside the window, every policy revokes the grant.
export function createTokenEndpoint({ db, privateKey, issuer, audience, clients, policy = "refuse", window = "10 seconds" }) {
async function tokenResponse(grant, scope, refreshToken) {
const accessToken = await new SignJWT({ client_id: grant.client_id, scope: scope.join(" "), sid: grant.grant_id })
.setProtectedHeader({ alg: "ES256", typ: "at+jwt" }) // RFC 9068: JWT access tokens
.setIssuer(issuer)
.setAudience(audience)
.setSubject(String(grant.user_id))
.setJti(randomUUID())
.setIssuedAt()
.setExpirationTime(`${ACCESS_TTL}s`)
.sign(privateKey);
return {
status: 200,
body: { access_token: accessToken, token_type: "Bearer", expires_in: ACCESS_TTL, refresh_token: refreshToken, scope: scope.join(" ") },
};
}
// Called when the authorization code grant completes: starts a grant and issues its first refresh token.
async function startGrant(userId, clientId, scope) {
const token = newRefreshToken();
const { rows } = await db.query(
`WITH g AS (INSERT INTO grants (user_id, client_id, scope, expires_at) VALUES ($1, $2, $3, now() + $4::interval)
RETURNING id, user_id, client_id)
INSERT INTO refresh_tokens (hash, grant_id, idle_expires_at) SELECT $5, id, now() + $6::interval FROM g
RETURNING grant_id, (SELECT user_id FROM g), (SELECT client_id FROM g)`,
[userId, clientId, scope, ABSOLUTE, sha256(token), IDLE],
);
return (await tokenResponse(rows[0], scope.split(" "), token)).body;
}
async function refresh(form) {
if (!form.refresh_token || !form.client_id) return error(400, "invalid_request");
if (!clients.includes(form.client_id)) return error(401, "invalid_client");
const c = await db.connect();
try {
await c.query("BEGIN");
// FOR UPDATE: concurrent requests with the same token wait here and then see each other's rotation.
const { rows: [t] } = await c.query(
`SELECT t.hash, t.rotated_at IS NOT NULL AS spent, t.rotated_at > now() - $2::interval AS in_window,
t.idle_expires_at > now() AS fresh, g.expires_at > now() AND g.revoked_at IS NULL AS live,
g.id AS grant_id, g.user_id, g.client_id, g.scope
FROM refresh_tokens t JOIN grants g ON g.id = t.grant_id
WHERE t.hash = $1
FOR UPDATE OF t`,
[sha256(form.refresh_token), window],
);
// Unknown, grant expired or revoked, or issued to another client (RFC 6749 section 5.2).
if (!t || !t.live || t.client_id !== form.client_id) return error(400, "invalid_grant");
if (t.spent && !(policy === "reuse-window" && t.in_window)) {
// A spent token came back. RFC 9700: the server can't tell which party is the thief, so it revokes the grant.
if (!(policy === "refuse" && t.in_window)) {
await c.query("UPDATE grants SET revoked_at = now(), revoked_why = 'refresh token reused' WHERE id = $1", [t.grant_id]);
}
await c.query("COMMIT");
return error(400, "invalid_grant");
}
if (!t.fresh) return error(400, "invalid_grant"); // unused too long (a spent token is a reuse, handled above)
const granted = t.scope.split(" ");
const scope = form.scope ? form.scope.split(" ") : granted;
if (!scope.every((s) => granted.includes(s))) return error(400, "invalid_scope"); // never wider than consented
if (!t.spent) await c.query("UPDATE refresh_tokens SET rotated_at = now() WHERE hash = $1", [t.hash]);
const next = newRefreshToken();
await c.query(
"INSERT INTO refresh_tokens (hash, grant_id, idle_expires_at) VALUES ($1, $2, now() + $3::interval)",
[sha256(next), t.grant_id, IDLE],
);
await c.query("COMMIT");
// The new refresh token keeps the full granted scope; only the access token is narrowed (RFC 6749 section 6).
return await tokenResponse(t, scope, next);
} finally {
await c.query("ROLLBACK").catch(() => {}); // no-op after COMMIT; ends the transaction on early returns
c.release();
}
}
async function handler(req, res) {
let out;
if (req.method !== "POST" || !req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) {
out = error(400, "invalid_request");
} else {
let raw = "";
for await (const chunk of req) raw += chunk;
const params = new URLSearchParams(raw);
const keys = [...params.keys()];
if (keys.length !== new Set(keys).size) out = error(400, "invalid_request"); // a parameter sent twice
else if (params.get("grant_type") !== "refresh_token") out = error(400, "unsupported_grant_type");
else out = await refresh(Object.fromEntries(params));
}
res.writeHead(out.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(JSON.stringify(out.body));
}
return { startGrant, handler };
}The decisions that make it correct:
- One transaction, one row lock.
SELECT … FOR UPDATEmakes concurrent refreshes of the same token wait for each other. The second one reads the row after the first has committed, seesrotated_atset, and takes the reuse path instead of rotating a second time. - Reuse is checked before anything else succeeds. A spent token is handled before the scope check, so a replay with an odd scope still counts as a replay.
- Revoking commits; refusing rolls back. When a reuse revokes the grant, that update is committed before the error goes out. Every other failure leaves the token exactly as it was, so a request with a bad scope or the wrong client doesn't spend the token.
- The refresh token keeps the full scope. RFC 6749 says a new refresh token must have the same scope as the one it replaces. Only the access token is narrowed when the client asks for less.
- The access token follows RFC 9068, the JWT profile for access tokens: header
typ: at+jwt, withclient_id,scope, and a uniquejti. Thesidclaim is the grant ID, so a resource server can check it against a denylist of revoked grants if it needs to.
What we tested#
The tests run three copies of the endpoint as real HTTP servers, one per reuse policy, against PostgreSQL 18, and call them with fetch. Nine checks passed:
- The response: status 200,
Cache-Control: no-store, the fields shown above, a new 32-byte refresh token every time, and an access token withtyp: at+jwtand a 600-second lifetime. - Errors: a password grant got
unsupported_grant_type; a duplicated parameter and a JSON body gotinvalid_request; an unknown client got 401invalid_client; an unknown token got 400invalid_grant. None of them spent the token. - Client binding: a token issued to
spawasinvalid_grantwhen presented asmobile, and still worked forspa. - Scope: asking for
orders:readnarrowed the access token; addingadmingotinvalid_scope; the next refresh without a scope got the full scope back. - Rotation: five refreshes produced six distinct tokens, five spent and kept in the table.
- Expiry and revocation: a token past its idle limit, a grant past its absolute limit, and a grant revoked after a password change all got
invalid_grant. A spent token past its idle limit still counted as a reuse (see below).
The remaining checks are about the hard part.
The reuse window: three policies#
Strictly applied, rotation treats every second use as theft. But a legitimate client produces second uses too. Two browser tabs can refresh at the same moment. A mobile app can send a refresh, lose its connection before the response arrives, and retry with the only token it has. Under strict rotation, both end with the user signed out for no reason.
RFC 9700 doesn't address this, so implementations differ. We implemented three policies for a spent token presented within 10 seconds of its rotation; after that, all three revoke the grant:
- strict: revoke, as for any reuse.
- refuse: answer
invalid_grant, but don't revoke. - reuse-window: exchange it again, issuing another valid refresh token. Several identity providers offer this as a setting: Auth0 calls it a reuse interval, Okta a grace period.
Then we ran four scenarios against each policy:
| Scenario | strict | refuse | reuse-window |
|---|---|---|---|
| Five tabs refresh with the same token at once | Grant revoked; user signed out | 1 succeeds; session continues | All 5 succeed; session continues |
| Response lost; the client retries with the same token | Grant revoked; user signed out | Retry refused; user signs in again | Retry succeeds; session continues |
| Attacker refreshes first; the user's copy arrives a minute later | Revoked; attacker out | Revoked; attacker out | Revoked; attacker out |
| Attacker replays the user's token 2 seconds after the user | Revoked; attacker out, user signed out | Attacker refused; user unaffected | Attacker gets a working token, undetected |
Every cell is an assertion in the tests. A separate check fired 20 refreshes of one token at once: the refuse policy issued exactly one new token, reuse-window issued 20, and neither revoked the grant.
strict is the simplest and catches the most, but it punishes ordinary races, so it needs a client that never sends the same token twice: one refresh at a time, across tabs too, and no retries. refuse costs nothing in security: within the window, the attacker gets nothing, and after it, reuse is still detected. Concurrent tabs are fine as long as they share the result. Its weak spot is the lost response: the client is left without a valid token, and the user signs in again. (The successor that never arrived stays valid but unknown to anyone, until its idle limit expires.) reuse-window survives every legitimate accident, but it opens a real hole: an attacker who uses a copied token within seconds of the user gets a working branch of the grant, and nothing ever flags it. An attacker able to read the token as it changes, such as a script injected into the page, can time that easily.
Keep spent tokens until the grant ends#
Spent tokens look like garbage, and a cleanup job that deletes them seems harmless. It isn't: detection depends on recognizing a spent token. Our test deleted the spent rows of a grant and then replayed the old token. The endpoint answered invalid_grant because it no longer knew the token, but it had no way to know it was a replay, and the grant stayed active. The attacker's branch, had there been one, would have survived. Delete tokens when their grant ends: the ON DELETE CASCADE does that when expired grants are purged.
For the same reason, the endpoint checks reuse before the idle limit. A spent token is a replay, however old it is: in our test, an attacker used a copied token, and the user's copy came back three weeks later, a week past its idle limit. The grant was revoked, and the attacker's token stopped working. Had the idle check come first, the user would have seen an ordinary expiry, and the attacker would have kept refreshing.
The cost is storage: one row per refresh, 99 bytes of row data in our table plus its index entries, kept for the life of the grant. With 10-minute access tokens, a user who is active eight hours a day adds about 50 rows a day.
The client's half#
Rotation also puts obligations on the client. It must replace its refresh token with the new one before doing anything else with the response, because the old one is now worthless; RFC 6749 already says the client must discard it. It must treat invalid_grant as the end of the session. And it must avoid sending the same token twice: one refresh at a time, shared by all requests and all tabs, as our access and refresh tokens article implements.
// client.mjs: the client's half of rotation. Store the new refresh token before doing anything else with the
// response, and drop the session when the server says the grant is gone.
export async function refreshTokens(store, tokenUrl, clientId) {
const res = await fetch(tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: store.refreshToken, client_id: clientId }),
});
const body = await res.json();
if (!res.ok) {
if (body.error === "invalid_grant") store.clear(); // revoked, expired or reused: the user signs in again
throw new Error(`refresh failed: ${body.error}`);
}
store.save({
accessToken: body.access_token,
refreshToken: body.refresh_token ?? store.refreshToken, // RFC 6749 lets a server keep the old one; RTR never does
expiresAt: Date.now() + body.expires_in * 1000,
});
return body.access_token;
}In the test, the client rotated three times, storing each new token. When a replay of its first token then revoked the grant, the next refresh threw on invalid_grant and cleared the stored session.
What rotation doesn't stop#
Rotation detects a copied token when both copies are used. It doesn't help when only one is:
- The user goes quiet. If the attacker copies the token and the user doesn't open the app again for a week, the attacker refreshes all week. Detection waits for the user's next refresh. The absolute lifetime is the backstop.
- The attacker keeps stealing. Malware or an injected script that can read each new token as it arrives always holds the current one. Rotation only helps against a one-time leak. The fix is to keep tokens out of reach: an
HttpOnlycookie, a backend-for-frontend, or the platform keychain. - Access tokens already issued. Revoking the grant stops refreshes, not access tokens that are already out. They work until they expire, which is why they should expire in minutes.
Rotation or sender-constrained tokens#
The other option in RFC 9700 binds the refresh token to a key that the client holds, using DPoP (RFC 9449) or mutual TLS (RFC 8705). A copied token is then useless without the private key.
| Rotation | Sender-constrained (DPoP) | |
|---|---|---|
| A copied token | Works until either party uses it a second time | Useless without the client's private key |
| The user is offline | Attacker refreshes until the user returns | Attacker can't refresh at all |
| Client changes | Store the new token after every refresh | Generate a key pair and sign a proof on every request |
| Server state | A row per issued token, kept until the grant ends | The key's thumbprint per grant |
| Concurrency issues | Races and lost responses, as above | None from the token itself |
| Weak spot | An attacker who can keep reading new tokens | An attacker who can use the key in place, such as script running in the page |
The two can be combined, and RFC 9700 allows either. Rotation is the one you can deploy with any client today.
FAQ#
Does a confidential client need rotation?
RFC 9700 doesn't require it: the client authenticates on every refresh, so a stolen refresh token alone isn't enough. Rotating anyway is harmless and limits damage if the client's credentials leak too.
Can refresh tokens be JWTs with rotation?
Yes, and RFC 9700 notes that the grant can be encoded in the token, as long as its integrity is protected, for example by a signature. But rotation still needs server state: the server has to remember which tokens are spent. A random token and a database row are simpler, and nothing about them can be decoded or forged.
What should the window be?
Long enough to cover a slow round trip and a retry, short enough that an attacker can't aim for it. A few seconds to 30 seconds is typical. The window only applies to the moments right after a rotation, never to a token that has been spent for longer.
Should a reused token also revoke the user's other sessions?
Usually not. Reuse shows that one grant leaked, on one device. Revoking all of the user's grants signs out every device for one leak. Some services do it for high-value accounts, together with a notification.
How do I look inside the access token the refresh returns?
Paste it into our JWT decoder: it shows the header (typ: at+jwt) and the claims, and can verify the signature with the authorization server's public key or JWKS.
Get the code
- jwt-dpop-sample on GitHub: refresh token rotation in an ASP.NET Core API, with encrypted (JWE) refresh tokens bound to a DPoP key; reusing a spent one revokes the session.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode the at+jwt access token from a refresh response and check its scope, client_id, and exp claims.
- Hash Generator: compute the SHA-256 of a refresh token, the value the database stores instead of the token.