Skip to content
Blog

← All articles

DPoP Explained: Binding Access Tokens to a Key (RFC 9449), and What It Doesn't Stop

A stolen bearer token works for whoever holds it. DPoP binds tokens to a key pair the client holds, so a copy is useless without the private key. A tested Web Crypto client with a non-extractable key, a token endpoint and API in Node.js, every way to misuse a proof, server nonces, the pre-generated proof attack that injected script can still pull off, the htu trap behind a proxy, and what it costs per request.

By 19 min read

An OAuth access token is usually a bearer token: whoever holds it can use it. That's what makes it simple, and it's also the problem. A token copied from a log, a proxy, a browser extension, a crash report, or a compromised dependency works just as well from the attacker's laptop as from your app, until it expires. The usual defense is to make tokens expire quickly and to rotate refresh tokens, which limits how long a copy is useful but not what it can do in that time.

DPoP (Demonstrating Proof of Possession, RFC 9449) changes what a token is. The client creates a key pair, the authorization server records the public key's fingerprint in every token it issues, and every request must carry a fresh signature from the private key. A copied token without the key is refused. This article builds all three parts (a browser client with nothing but Web Crypto, a token endpoint, and an API), tests every way we could think of to misuse a token or a proof, and measures the one attack DPoP doesn't stop on its own. Several of our earlier articles name DPoP as the answer to a stolen token; this is how it actually works.

Prefer video? There’s a fourteen-minute version that builds the client, the token endpoint and the API, then attacks them. All the code is also on GitHub, with the tests that run every attack over HTTP: dpop-sample.

Nothing loads from YouTube until you press play. Watch on YouTube

The short answer#

The problem with bearer tokens#

A JWT access token is signed, so nobody can change it, but nothing in it says who may present it. The resource server checks the signature, the issuer, the audience, and the expiry, and if they're fine, the request is authorized, regardless of who sent it. TLS protects the token in transit; it does nothing once the token is at rest on either end. A short lifetime limits the damage to minutes, and revocation lists can cut it shorter, but a copy still works everywhere until then.

Sender-constrained tokens fix this: the token is only valid together with proof that the sender holds a particular key. RFC 9700, the current OAuth security best practice, recommends them, and offers two ways to do it: mutual TLS (RFC 8705), which binds the token to the client's TLS certificate, and DPoP, which works at the HTTP layer and so works in a browser, behind load balancers, with no certificates at all. The FAPI 2.0 security profile, used for open banking, requires one of the two, and Bluesky's AT Protocol requires DPoP for every OAuth client.

How DPoP works#

  1. The client generates a key pair once, when the user logs in (or keeps one per device), and never sends the private key anywhere.
  2. On the token request, it adds a DPoP header: a proof JWT that contains the public key and is signed with the private key. The authorization server checks it, puts the key's thumbprint in the access token as cnf.jkt, and answers with token_type: "DPoP" instead of Bearer.
  3. On every API call, the client sends the token using the DPoP scheme instead of Bearer, along with a new proof for that exact request, which this time includes a hash of the token.
  4. The API checks the token as usual, then checks the proof: signed by the key the token names, for this method and URL, recent, for this token, and never seen before.
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...

grant_type=authorization_code&code=...&code_verifier=...&client_id=spa&redirect_uri=...

HTTP/1.1 200 OK
Cache-Control: no-store

{"access_token":"eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9...","token_type":"DPoP","expires_in":300,"refresh_token":"..."}

GET /orders HTTP/1.1
Host: api.example.com
Authorization: DPoP eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9...
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...

The proof#

A proof is an ordinary JWS with a special header. Here is one our client made, decoded (the signature isn't shown):

// header
{
  "typ": "dpop+jwt",
  "alg": "ES256",
  "jwk": {
    "kty": "EC",
    "crv": "P-256",
    "x": "xatMdllW95KPVPs8o1hr9mrxKCn1mx1Z0YZm9nqUII0",
    "y": "Y8mJuyFwHsV00LWfsfbqOtldnI1nsLe2cSWVQTfaNOA"
  }
}
// claims
{
  "jti": "c52f934e-662e-49e3-b617-b45a1b119216",
  "htm": "GET",
  "htu": "https://api.example.com/orders",
  "iat": 1794651011,
  "ath": "vf7KW8mAaOPEQ-BiHqJIiowbx-GO-qZWHJqpmVeON0o"
}
FieldWhat it isWhat it stops
typdpop+jwtAnother kind of JWT, such as an ID token, being passed off as a proof
alg, jwkAn asymmetric algorithm, and the public key itselfThe proof checks itself; the token decides whether this is the right key
jtiA unique IDThe same proof being sent twice
htm, htuThe HTTP method and URL, without the query or fragmentA proof for GET /orders being used for DELETE /orders or /admin
iatWhen it was madeAn old proof being kept and used later (there's no exp: the server decides how old is too old)
athbase64url(SHA-256(access token)), on API calls onlyA proof being paired with a different token
nonceA value the server sent, if it asks for oneProofs made in advance (see below)

The key's thumbprint (RFC 7638) is what ties the proof to the token. It's the SHA-256 of the key's required members in alphabetical order with no whitespace, so for this key {"crv":"P-256","kty":"EC","x":"…","y":"…"}, base64url-encoded: 43 characters, here o2ZmxbyFvrvEeQpFaZ9ThS0u34z_ke4kKJdToDQU6hk. Our test computed it by hand and got the same value as jose's calculateJwkThumbprint. Because the format is fixed, the same key always has the same thumbprint, regardless of how its JSON is written.

The client: Web Crypto, no library#

A proof needs a JSON encoder, base64url, and one signature, all of which the browser already has. This file runs unchanged in a browser and in Node.js 24:

dpop-proof.mjs
// dpop-proof.mjs: DPoP proofs (RFC 9449) with nothing but Web Crypto. Runs unchanged in browsers and Node.js 24.
const enc = new TextEncoder();
export const b64url = (bytes) =>
  btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const part = (obj) => b64url(enc.encode(JSON.stringify(obj)));

// A P-256 key pair whose private half can sign but can never be exported, not even by our own code.
export const createDpopKey = () =>
  crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);

export async function createProof(keyPair, { method, url, accessToken, nonce }) {
  const { kty, crv, x, y } = await crypto.subtle.exportKey("jwk", keyPair.publicKey); // the public half always exports
  const target = new URL(url);
  const header = { typ: "dpop+jwt", alg: "ES256", jwk: { kty, crv, x, y } };
  const claims = {
    jti: crypto.randomUUID(),              // unique, so the server can refuse a replay
    htm: method,                           // the HTTP method ...
    htu: target.origin + target.pathname,  // ... and URL it is for, without the query or fragment
    iat: Math.floor(Date.now() / 1000),    // when it was made; there is no exp
  };
  if (accessToken) claims.ath = b64url(await crypto.subtle.digest("SHA-256", enc.encode(accessToken)));
  if (nonce) claims.nonce = nonce;         // the server's latest DPoP-Nonce, if it sent one
  const input = `${part(header)}.${part(claims)}`;
  const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, keyPair.privateKey, enc.encode(input));
  return `${input}.${b64url(signature)}`; // Web Crypto's ECDSA output is already r || s, the form JWS uses
}

The important part is the second argument to generateKey, false: the private key is non-extractable. Our test confirmed that exportKey on it throws an error, while the public key still exports (Web Crypto always makes the public half extractable). Code running in the page can ask the key to sign, but no code, including an attacker's, can read the key out and send it somewhere. Two other details: new URL() lowercases the host and drops a default port, so htu comes out normalized; and Web Crypto's ECDSA signature is already the 64-byte r || s that JWS uses, unlike Node's crypto.sign, which defaults to DER.

To survive a page reload, the key pair goes into IndexedDB, which stores the CryptoKey objects themselves rather than their bytes:

key-store.mjs
// key-store.mjs: keep the DPoP key pair in IndexedDB, so it survives a page reload.
// IndexedDB stores the CryptoKey object itself; the private key stays non-extractable.
const request = (req) => new Promise((resolve, reject) => {
  req.onsuccess = () => resolve(req.result);
  req.onerror = () => reject(req.error);
});

export async function loadOrCreateKey(create) {
  const open = indexedDB.open("dpop", 1);
  open.onupgradeneeded = () => open.result.createObjectStore("keys");
  const db = await request(open);
  try {
    const saved = await request(db.transaction("keys").objectStore("keys").get("current"));
    if (saved) return saved;
    const keyPair = await create();
    await request(db.transaction("keys", "readwrite").objectStore("keys").put(keyPair, "current"));
    return keyPair;
  } finally {
    db.close();
  }
}

Our test stored a key pair, loaded it again, and verified that it had the same thumbprint, remained non-extractable, and still signed valid proofs. (Node.js has no IndexedDB, so the test used fake-indexeddb, which clones values the same way a browser does.) Losing the key means losing the tokens bound to it: if the user clears site data, they have to log in again, which is the point.

Then a wrapper around fetch that adds a proof to every request:

dpop-fetch.mjs
// dpop-fetch.mjs: fetch() with a fresh DPoP proof on every request, and the server's nonce handled.
import { createProof } from "./dpop-proof.mjs";

export function createDpopFetch(keyPair) {
  const nonces = new Map(); // origin -> the last DPoP-Nonce that server sent

  async function send(url, { method = "GET", accessToken, headers = {}, body }) {
    const proof = await createProof(keyPair, { method, url, accessToken, nonce: nonces.get(new URL(url).origin) });
    const auth = accessToken ? { Authorization: `DPoP ${accessToken}` } : {};
    const res = await fetch(url, { method, body, headers: { ...headers, ...auth, DPoP: proof } });
    const nonce = res.headers.get("DPoP-Nonce");
    if (nonce) nonces.set(new URL(url).origin, nonce);
    return { res, nonce };
  }

  return async function dpopFetch(url, options = {}) {
    const { res, nonce } = await send(url, options);
    if (!nonce || !(await askedForNonce(res))) return res;
    return (await send(url, options)).res; // once more: a new proof that carries the new nonce
  };
}

// A token endpoint asks in a 400 JSON body; a resource server in its WWW-Authenticate header.
async function askedForNonce(res) {
  if (res.status === 401) return /error="use_dpop_nonce"/.test(res.headers.get("WWW-Authenticate") ?? "");
  if (res.status === 400) return (await res.clone().json().catch(() => ({}))).error === "use_dpop_nonce";
  return false;
}

The nonce handling is explained below; if the server doesn't use nonces, it's never triggered. Note that every call, including the retry, signs a new proof with a new jti: a proof is never reused, even by the client that made it.

Binding tokens at the token endpoint#

Both the token endpoint and the API perform the same proof check, so it lives in a single file. It follows the list in section 4.3 of RFC 9449:

dpop-verify.mjs
// dpop-verify.mjs: checking a DPoP proof (RFC 9449, section 4.3). Used by the token endpoint and the API.
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { calculateJwkThumbprint, EmbeddedJWK, jwtVerify } from "jose";

export const ALGORITHMS = ["ES256", "EdDSA", "PS256", "RS256"]; // asymmetric only: never "none", never HS256
export class DpopError extends Error {
  constructor(code, message) { super(message); this.code = code; } // invalid_dpop_proof or use_dpop_nonce
}
const fail = (why) => { throw new DpopError("invalid_dpop_proof", why); };
const sha256 = (s) => createHash("sha256").update(s).digest("base64url");
const withoutQuery = (url) => { // also lowercases the scheme and host, and drops a default port
  try { const u = new URL(url); return u.origin + u.pathname; } catch { return null; }
};

export async function verifyDpopProof(proof, { method, url, accessToken, jkt, nonces, markUsed,
                                               now = Date.now, maxAge = 60, leeway = 5 }) {
  if (typeof proof !== "string" || !proof || proof.includes(",")) fail("send exactly one DPoP header");
  let payload, protectedHeader;
  try { // the key is the one in the proof's own jwk header; jose refuses a private key there
    ({ payload, protectedHeader } = await jwtVerify(proof, EmbeddedJWK, { typ: "dpop+jwt", algorithms: ALGORITHMS }));
  } catch (e) { fail(e.message); }
  const { jti, htm, htu, iat, ath, nonce } = payload;
  const t = Math.floor(now() / 1000);
  if (typeof jti !== "string" || jti.length > 128) fail("jti missing or too long");
  if (htm !== method) fail("proof is for another HTTP method");
  if (typeof htu !== "string" || withoutQuery(htu) !== withoutQuery(url)) fail("proof is for another URL");
  if (typeof iat !== "number" || iat > t + leeway || iat < t - maxAge) fail("proof is too old, or dated in the future");
  if (accessToken !== undefined && ath !== sha256(accessToken)) fail("proof is for another access token");
  const thumbprint = await calculateJwkThumbprint(protectedHeader.jwk, "sha256"); // RFC 7638
  if (jkt !== undefined && thumbprint !== jkt) fail("the token is bound to another key");
  if (nonces && !nonces.valid(nonce)) throw new DpopError("use_dpop_nonce", "use the DPoP-Nonce we sent");
  if (!(await markUsed(`dpop:${thumbprint}:${jti}`, maxAge + 2 * leeway))) fail("proof already used");
  return { jkt: thumbprint, claims: payload };
}

// Stateless nonces: an HMAC of the current minute. Every instance with the secret agrees, nothing is stored,
// and a nonce stays good for one to two minutes (this minute's or the last one's).
export function createNonces(secret, { step = 60, now = Date.now } = {}) {
  const at = (n) => createHmac("sha256", secret).update(String(n)).digest("base64url");
  const slot = () => Math.floor(now() / 1000 / step);
  const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
  return {
    current: () => at(slot()),
    valid: (nonce) => typeof nonce === "string" && [slot(), slot() - 1].some((n) => same(nonce, at(n))),
  };
}

// Single-process replay store. With several instances, share it in Redis (see the jti articles):
//   const markUsed = async (key, ttl) => (await redis.set(key, "1", "EX", ttl, "NX")) === "OK";
export function memoryReplayStore(now = Date.now) {
  const seen = new Map(); // key -> expiry in ms
  return async (key, ttl) => {
    if (seen.size > 100_000) for (const [k, until] of seen) if (until <= now()) seen.delete(k);
    if ((seen.get(key) ?? 0) > now()) return false;
    seen.set(key, now() + ttl * 1000);
    return true;
  };
}
  • The key comes from the proof itself (jose's EmbeddedJWK). That's safe here, unlike in an ordinary JWT, because the signature only proves possession; whether it's the right key is decided by comparing the thumbprint with the token's cnf.jkt.
  • An explicit list of asymmetric algorithms. An HMAC "proof" would prove nothing, since the secret would have to be in the header.
  • Time: up to 60 seconds old, up to 5 seconds ahead. The replay key is kept for 70 seconds, longer than any proof can be accepted, the same rule as in our jti article. The key includes the thumbprint, so one client's IDs can never collide with another's.
  • The replay store must be shared by every instance that accepts proofs; the in-memory one is for a single process. Our production article covers what happens to a Redis store during failover and under memory pressure.

The token endpoint verifies the proof first, then binds what it issues to that key:

token-endpoint.mjs
// token-endpoint.mjs: an authorization server's token endpoint that binds every token it issues to the
// client's DPoP key. For a public client (a browser app with PKCE); no client secret.
import { createHash, randomBytes } from "node:crypto";
import { SignJWT } from "jose";
import { DpopError, verifyDpopProof } from "./dpop-verify.mjs";

export function createTokenEndpoint({ issuer, tokenUrl, audience, signingKey, codes, nonces, markUsed, now = Date.now }) {
  const grants = new Map(); // refresh token -> { sub, clientId, scope, jkt }: the key is part of the grant

  const reply = (status, body) => ({
    status, body,
    headers: { "Cache-Control": "no-store", ...(nonces && { "DPoP-Nonce": nonces.current() }) },
  });

  return async function handle({ headers, form }) {
    let proof;
    try {
      proof = await verifyDpopProof(headers.dpop, { method: "POST", url: tokenUrl, nonces, markUsed, now });
    } catch (e) {
      if (e instanceof DpopError) return reply(400, { error: e.code, error_description: e.message });
      throw e;
    }

    let grant, refreshToken;
    if (form.grant_type === "authorization_code") {
      const code = codes.take(form.code); // single use
      const pkce = createHash("sha256").update(form.code_verifier ?? "").digest("base64url");
      if (!code || code.clientId !== form.client_id || code.redirectUri !== form.redirect_uri || pkce !== code.challenge)
        return reply(400, { error: "invalid_grant" });
      grant = { sub: code.sub, clientId: code.clientId, scope: code.scope, jkt: proof.jkt }; // bind to this key
      refreshToken = randomBytes(32).toString("base64url");
      grants.set(refreshToken, grant);
    } else if (form.grant_type === "refresh_token") {
      grant = grants.get(form.refresh_token);
      if (!grant || grant.clientId !== form.client_id) return reply(400, { error: "invalid_grant" });
      if (grant.jkt !== proof.jkt) return reply(400, { error: "invalid_grant", error_description: "bound to another key" });
    } else {
      return reply(400, { error: "unsupported_grant_type" });
    }

    const iat = Math.floor(now() / 1000);
    const accessToken = await new SignJWT({ client_id: grant.clientId, scope: grant.scope, cnf: { jkt: grant.jkt } })
      .setProtectedHeader({ alg: "ES256", typ: "at+jwt" })
      .setIssuer(issuer).setSubject(grant.sub).setAudience(audience)
      .setIssuedAt(iat).setExpirationTime(iat + 300)
      .sign(signingKey);
    return reply(200, {
      access_token: accessToken, token_type: "DPoP", expires_in: 300, scope: grant.scope,
      ...(refreshToken && { refresh_token: refreshToken }),
    });
  };
}

// What the /authorize endpoint does after the user logs in: a one-time code tied to the PKCE challenge.
export function createCodeStore() {
  const codes = new Map();
  return {
    issue(details) { const code = randomBytes(16).toString("base64url"); codes.set(code, details); return code; },
    take(code) { const details = codes.get(code); codes.delete(code); return details; },
  };
}

For a public client, such as a browser app, RFC 9449 also requires the refresh token to be bound, because there's no client secret to stop a stolen one being used. Here the key's thumbprint is stored with the grant, and a refresh with any other key is refused. A confidential client that authenticates on every refresh doesn't need that, but its access tokens can be bound all the same. RFC 9449 also has an optional dpop_jkt parameter that binds the authorization code to the key at the start of the flow; we rely on PKCE for the code and didn't implement it.

Checking a request at the API#

resource-server.mjs
// resource-server.mjs: an API that accepts only DPoP-bound access tokens, each with a proof for this request.
import { jwtVerify } from "jose";
import { ALGORITHMS, DpopError, verifyDpopProof } from "./dpop-verify.mjs";

export function createAuthenticator({ issuer, audience, issuerKey, publicOrigin, nonces, markUsed, now = Date.now }) {
  const deny = (error, description) => {
    const params = error ? `error="${error}", error_description="${description.replace(/["\\]/g, "'")}", ` : "";
    return {
      ok: false, status: 401,
      headers: {
        "WWW-Authenticate": `DPoP ${params}algs="${ALGORITHMS.join(" ")}"`,
        ...(nonces && { "DPoP-Nonce": nonces.current() }),
      },
    };
  };

  return async function authenticate({ method, path, headers }) {
    const [scheme, token] = (headers.authorization ?? "").split(" ");
    if (!token) return deny(); // no credentials: just say which scheme and algorithms we take
    let claims;
    try {
      ({ payload: claims } = await jwtVerify(token, issuerKey,
        { issuer, audience, typ: "at+jwt", algorithms: ["ES256"], currentDate: new Date(now()) }));
    } catch {
      return deny("invalid_token", "bad or expired access token");
    }
    if (!claims.cnf?.jkt) return deny("invalid_token", "this API accepts only DPoP-bound tokens");
    if (scheme.toLowerCase() !== "dpop") return deny("invalid_token", "a DPoP-bound token sent as Bearer");
    try {
      // The URL the client signed is the public one, so build it from configuration, never from Host headers.
      await verifyDpopProof(headers.dpop, {
        method, url: publicOrigin + path, accessToken: token, jkt: claims.cnf.jkt, nonces, markUsed, now,
      });
    } catch (e) {
      if (e instanceof DpopError) return deny(e.code, e.message);
      throw e;
    }
    return { ok: true, claims, headers: nonces ? { "DPoP-Nonce": nonces.current() } : {} };
  };
}
  • A DPoP-bound token sent as Bearer is refused. Otherwise, an attacker would just change the scheme and omit the proof. RFC 9449 requires this of any resource server that accepts both schemes.
  • The proof must be for this token (ath) and this key (cnf.jkt). Together, the two checks mean that neither a stolen token with a new proof nor a stolen proof with another token gets through.
  • Errors use WWW-Authenticate, as RFC 9449 specifies. A proof from the wrong key produced this header in our test: DPoP error="invalid_dpop_proof", error_description="the token is bound to another key", algs="ES256 EdDSA PS256 RS256". A request with no token at all gets just the scheme and the algorithms.

What we tested#

The token endpoint and the API ran as HTTP servers on Node.js 24 with jose 6.2. The client was the Web Crypto code above. Ten checks passed; these are the attacks:

AttemptResult
A stolen access token sent as Bearer401 invalid_token
The stolen token as DPoP, with no proof401 invalid_dpop_proof
The stolen token with a valid proof from the attacker's own key401: bound to another key
A stolen refresh token, with the attacker's key400 invalid_grant
The same proof sent twice200, then 401: proof already used
A proof for GET sent with DELETE401: another HTTP method
A proof for /orders sent to /admin401: another URL
A proof for the old access token, sent with the refreshed one401: another access token
A proof 61 seconds old, or 30 seconds in the future401: too old, or dated in the future
alg: none; HS256 with an oct key in the headerRefused: algorithm not allowed
A private key in the jwk header; no jwk; typ: JWTRefused by jose
Two DPoP headersRefused: exactly one is allowed
A proof whose signature is from a different key than its jwkRefused: signature verification failed

And what should pass did: a proof 4 seconds in the future (inside the leeway), a proof for /orders used on /orders?page=2 (the query isn't signed), an uppercase host with an explicit :443, and Ed25519 proofs alongside ES256. A different port, :8443, was a different URL. As an independent check, oauth4webapi 3.8, a certified OpenID client library, logged in and called the API against our servers with server nonces switched on, retrying once at each.

Server nonces#

A server can require proofs to include a value it chose. It refuses a proof without the current one and sends it back in a DPoP-Nonce header: the token endpoint with 400 and {"error":"use_dpop_nonce"}, the API with 401 and WWW-Authenticate: DPoP error="use_dpop_nonce". The client makes a new proof with the nonce and tries again, and from then on includes the latest nonce the server sent.

Our nonces are stateless: an HMAC of the current minute using a server secret, accepted for the current minute and the one before. Every instance with the secret agrees, and nothing is stored. In the test, the first token request and the first API call each took two requests (refused, then accepted); after that each call took one. A nonce a minute old was still accepted; after three minutes it was refused, and the client recovered with one retry. The cost is an extra round trip on the first call to each server, and whenever the nonce changes while the client is idle.

Without nonces, DPoP still works, and RFC 9449 makes them optional. What they add is protection against one specific attack, which is the honest limit of DPoP in a browser.

What DPoP doesn't stop: script in the page#

If an attacker gets script running in your page (XSS, a compromised npm package, a malicious extension), a non-extractable key doesn't stop them using it. While their code runs, it can call your API with valid proofs exactly as your code does. DPoP doesn't help with that, and nothing else stored in the browser does either. What a non-extractable key should do is make the attack end when the script stops. Without nonces, it doesn't quite:

pregenerate.mjs
// pregenerate.mjs: what injected script can do with a key it cannot export. It signs proofs now, dated in
// the future, and sends them home with the access token, to use after the user has closed the tab.
import { createProof } from "./dpop-proof.mjs";

export async function pregenerate(keyPair, { url, accessToken, nonce, minutes }) {
  const realNow = Date.now;
  const proofs = [];
  try {
    for (let m = 1; m <= minutes; m++) {
      Date.now = () => realNow() + m * 60_000; // the page's clock is the attacker's clock
      proofs.push({ minute: m, proof: await createProof(keyPair, { method: "GET", url, accessToken, nonce }) });
    }
  } finally {
    Date.now = realNow;
  }
  return proofs;
}

The script can't export the key, but the page's clock is under its control, so it signs proofs dated in the future and sends them home with the access token. In our test, it signed six proofs, dated one to six minutes ahead. With the server's clock moved forward, the attacker used the 3-minute and 4-minute proofs from a plain HTTP client with no key at all: both got 200. The 6-minute one failed only because the access token itself had expired at 5 minutes. A pre-generated proof is good for as long as the access token it was made for.

With server nonces on, the same attack is limited to the nonce's lifetime. The script made its proofs with the nonce the page had; the 1-minute proof still worked (the nonce was still accepted), and the 3- and 4-minute proofs were refused with use_dpop_nonce. The attacker can't answer, because the new nonce goes to whoever asks, and generating a proof with it requires the key, which stayed in the victim's browser.

Behind a proxy: the htu trap#

The client signs the URL it calls: the public one, such as https://api.example.com/orders. Behind CloudFront, an ALB, or nginx, the API often receives something else: http instead of https where TLS ends at the proxy, another port, or an internal hostname (nginx's proxy_pass and CloudFront both replace the Host header by default; an ALB keeps it). An API that rebuilds the URL from the request it receives compares the signed URL with the wrong one, and refuses every proof. We put the API behind a small reverse proxy that rewrote the Host header. Built from configuration (publicOrigin), the check accepted the request; the same API, building the URL from the Host header it saw, refused it: "proof is for another URL".

So configure the public origin explicitly. Building it from X-Forwarded-Host and X-Forwarded-Proto works only if your proxy always overwrites them; if a client can set them, it can choose which URL its proof is checked against. Watch out for path rewrites too: a proxy that strips /api from the path breaks htu the same way.

What it costs#

AlgorithmProof sizeMake a proofCheck a proof
ES256 (P-256)530 bytes93 µs266 µs
EdDSA (Ed25519)468 bytes88 µs206 µs
RS256 (2048-bit)1,116 bytes473 µs200 µs

Measured on Node.js 24 with Web Crypto, 2,000 proofs each, with ath (a second run was within 6% on every figure); "check" is the whole verifyDpopProof above, including the thumbprint and the replay store. Every request gets about half a kilobyte bigger (our access token was 400 bytes, so the proof is larger than the token), and each side spends a fraction of a millisecond. ES256 is the safe default: every browser supports it in Web Crypto, and it's the algorithm authorization servers most often support for DPoP. Ed25519 is a little smaller and faster where it's supported. RSA keys make proofs twice the size; avoid them for DPoP. Our article on elliptic curves explains what the two curves are.

The real costs are elsewhere: a replay store every API instance shares, a retry path for nonces, an API that knows its public URL, and support from your authorization server. Many identity providers support DPoP now, but check that yours binds refresh tokens for public clients and that your API gateway or library can check proofs, not just tokens.

DPoP, mutual TLS, or a BFF#

DPoPMutual TLS (RFC 8705)Backend for frontend
Where tokens liveIn the client, bound to its keyIn the client, bound to its certificateOn your server; the browser gets an HttpOnly cookie
Works in a browserYesNot in practiceYes
Behind load balancersYes, if the API knows its public URLOnly if TLS is terminated where the certificate can be checkedYes
A stolen tokenUseless without the keyUseless without the certificate's keyNever reaches the browser
Injected scriptCan act while it runs; pre-generated proofs unless noncesn/aCan act while it runs, through the cookie
Per requestOne signature, ~0.5 KBNothing extra after the handshakeA hop through your server

For service-to-service calls where you control TLS end to end, mutual TLS is cheaper per request. For a browser app, the choice is between DPoP and a backend for frontend, a small server that holds the tokens and gives the browser a session cookie. A BFF keeps tokens out of the browser entirely, which is why the IETF's guidance for browser apps puts it first; DPoP is the better option when the app has to call APIs directly, from a browser, a mobile app, or a CLI, without a server of its own in the middle. The two don't exclude each other: a BFF can use DPoP for its own tokens, and DPoP can be combined with refresh token rotation.

FAQ#

Does DPoP replace short-lived access tokens?

No. The pre-generated proofs above kept working until the access token expired, so the lifetime still limits the damage. Five minutes, as in our tests, is reasonable; with DPoP you can afford a little longer than with bearer tokens, not hours.

Should the client make a new key for each login?

A new key per login is simplest: the key's life matches the session's, and logging out can delete it. Keeping one key per device also works, but then the key outlives sessions and any token bound to it. Either way, keep the private key non-extractable.

Can a server-side or mobile client use DPoP?

Yes; nothing in it is browser-specific. A mobile app can keep the key in hardware (the Secure Enclave, or a hardware-backed Android Keystore), which is stronger than a browser can offer: the private key never exists in the app's memory, so even malware that can read that memory can't copy it.

Do I need to store every proof's jti?

RFC 9449 only requires that proofs be accepted for a short time; storing each jti for that time is something a server "can" do, and the RFC admits strict single use isn't always practical. Without it, a captured proof can be replayed to the same URL until it ages out: in our test, the second copy was refused only because the store had seen its jti. We'd keep it. It costs about a minute of storage per request, and with several API instances, the store has to be shared, or a copy sent to a different instance gets through.

How do I check what a proof or token contains?

Paste it into our JWT decoder: for a proof, you'll see the jwk header and the htm, htu, iat, and ath claims; for an access token, its cnf.jkt, which should equal the thumbprint of the proof's key.

Get the code

  • dpop-sample on GitHub: every example from this article, with the tests that run them over HTTP: stolen tokens, replayed and forged proofs, server nonces, pre-generated proofs and the proxy trap.
  • jwt-dpop-sample on GitHub: an ASP.NET Core API and Angular app that use DPoP: a non-extractable key in the browser, the proof checks from this article, server nonces, and an attack lab where the API refuses stolen tokens and replayed proofs.

Try it in your browser