DPoP proofs
Bind an access token to the client's key, so a stolen token is useless without the key that goes with it.
A bearer token works for whoever holds it, like a concert ticket. DPoP (RFC 9449) puts the holder's photo on the ticket: the client keeps a key pair, the authorization server writes the public key's thumbprint into the access token, and on every request the client signs a short JWT, the proof, with the private key. The proof names the request's method and URL and the time it was made, and can carry a hash of the access token and a nonce the server handed out. Your API checks that the proof is fresh, is for this request, and is signed by the key the token names. Concepts covers the JWT vocabulary.
#Before you start
- Import from
unjwt/dpop. It's a separate entry: nothing else in unjwt imports it. - DPoP keys are asymmetric:
ES256,EdDSA,RS256and the rest of the signing algorithms exceptHS*. A shared secret can't prove who holds it. - The client keeps its key pair for as long as the tokens bound to it live. A new pair means a new token.
- unjwt creates and checks proofs. Sending them, validating the access token, issuing nonces and remembering proofs you've seen are yours, and each has a sketch below.
- A target is
{ method, url }, and a WebRequestis one. Behind a proxy, pass the URL the client used, not the one your server sees.
#Send proofs from the client
createDPoPProof(target, options) signs a proof for one request. This client sends one with every request and tries once more when the server asks for a nonce:
import { createDPoPProof } from "unjwt/dpop";
import { generateJWK } from "unjwt/jwk";
type Send = (request: Request) => Promise<Response>;
export interface DPoPClient {
request(method: string, url: string, accessToken?: string): Promise<Response>;
}
/** A client that holds one key pair and proves it on every request. */
export async function createClient(send: Send = fetch): Promise<DPoPClient> {
// Keep the pair for as long as the tokens bound to it live.
const keyPair = await generateJWK("ES256");
let nonce: string | undefined;
async function attempt(method: string, url: string, accessToken?: string): Promise<Response> {
const proof = await createDPoPProof(
{ method, url },
{ keyPair, nonce, accessToken: accessToken ? { token: accessToken } : undefined },
);
const headers = new Headers({ dpop: proof });
if (accessToken) headers.set("authorization", `DPoP ${accessToken}`);
const response = await send(new Request(url, { method, headers }));
nonce = response.headers.get("dpop-nonce") ?? nonce;
return response;
}
/** One request, sent a second time when the server asks for a fresh nonce. */
async function request(method: string, url: string, accessToken?: string): Promise<Response> {
const response = await attempt(method, url, accessToken);
const challenge = response.headers.get("www-authenticate") ?? "";
if (response.status !== 401 || !challenge.includes('error="use_dpop_nonce"')) return response;
return attempt(method, url, accessToken);
}
return { request };
}keyPair: a JWK pair fromgenerateJWK, or aCryptoKeyPairwhose public half is extractable. The private key may be non-extractable.- Algorithm: inferred from the private or public JWK's
alg, or from a key shape with one answer, such as a P-256 curve forES256. Passalgorithmfor aCryptoKeyPairor an RSA key withoutalg. jtiandiat: every proof gets a fresh UUID v4 and the current second. Override them only in tests: a proof id is never reused.accessToken: { token }: addsath, the SHA-256 of the exact token, so the proof can't travel with another token.nonce: copies the server's latestDPoP-Nonceinto the proof.expandnbf: optional absolute times in seconds, written only when you pass them. They narrow a proof's window; they never widen the server's age limit.
#Bind the token at the token endpoint
At the token endpoint, verify the proof on its own and write its key's thumbprint into the token as cnf.jkt:
import { isJWTError, verifyDPoPProof, type DPoPVerifyResult } from "unjwt/dpop";
import { generateJWK } from "unjwt/jwk";
import { sign, verify } from "unjwt/jws";
import { base64UrlStringify, secureRandomBytes } from "unjwt/utils";
import { hash } from "unsecure/hash"; // WebCrypto API
const ISSUER = "https://auth.example.com";
const API = "https://api.example.com";
const MAX_AGE = 60;
const TOLERANCE = 5;
// The issuer's key pair, loaded once at start-up: see /jwk/generate.
/** `POST /token`, once your own code has authenticated the user. */
export async function tokenEndpoint(request: Request, userId: string) {
const proof = request.headers.get("dpop");
if (!proof || proof.includes(",")) {
return Response.json({ error: "invalid_dpop_proof" }, { status: 400 });
}
let thumbprint: string;
try {
({ thumbprint } = await verifyDPoPProof(proof, request, {
algorithms: ["ES256", "EdDSA"],
maxTokenAge: MAX_AGE,
clockTolerance: TOLERANCE,
consumeProof: consumeOnce,
}));
} catch (error) {
if (isProofRejection(error)) {
return Response.json({ error: "invalid_dpop_proof" }, { status: 400 });
}
throw error;
}
const token = await sign(
{ iss: ISSUER, aud: API, sub: userId, cnf: { jkt: thumbprint } },
privateKey,
{
expiresIn: "10m",
protectedHeader: { typ: "at+jwt" },
},
);
return Response.json({ access_token: token, token_type: "DPoP", expires_in: 600 });
}verifyDPoPProof returns { payload, thumbprint }. The thumbprint is the RFC 7638 SHA-256 of the proof's public key, the same value thumbprint() gives for that key. The RFC answers a bad proof here with a 400 and invalid_dpop_proof.
#Check proofs at the API
At the API, validate the access token first, then the proof against it:
/** `GET /orders`, for `Authorization: DPoP <token>` plus one `DPoP` proof header. */
export async function ordersEndpoint(request: Request) {
const authorization = request.headers.get("authorization") ?? "";
const proof = request.headers.get("dpop");
if (!authorization.startsWith("DPoP ") || !proof || proof.includes(",")) {
return challenge("invalid_request");
}
const accessToken = authorization.slice(5);
// 1. The access token is yours to validate. Its cnf.jkt names the bound key.
let claims: { sub?: string; cnf?: { jkt?: string } };
try {
({ payload: claims } = await verify(accessToken, publicKey, {
algorithms: ["ES256"],
typ: "at+jwt",
issuer: ISSUER,
audience: API,
}));
} catch (error) {
if (isJWTError(error) && error.code !== "ERR_INVALID_OPTION") return challenge("invalid_token");
throw error;
}
const jkt = claims.cnf?.jkt;
if (!jkt) return challenge("invalid_token");
// 2. The proof: this request, this token, the key the token is bound to.
try {
await verifyDPoPProof(proof, request, {
algorithms: ["ES256", "EdDSA"],
maxTokenAge: MAX_AGE,
clockTolerance: TOLERANCE,
nonce: currentNonce(),
accessToken: { token: accessToken, thumbprint: jkt },
consumeProof: consumeOnce,
});
} catch (error) {
if (isJWTError(error, "ERR_DPOP_NONCE_INVALID")) {
return challenge("use_dpop_nonce", { "dpop-nonce": currentNonce() });
}
if (isProofRejection(error)) return challenge("invalid_dpop_proof");
throw error;
}
return Response.json({ sub: claims.sub, orders: [] });
}
/** A rejected proof, as opposed to a misconfigured server or a replay store that failed. */
function isProofRejection(error: unknown): boolean {
if (isJWTError(error, "ERR_DPOP_REPLAY")) return error.cause === undefined;
return isJWTError(error, "ERR_DPOP_INVALID") || isJWTError(error, "ERR_DPOP_CLAIM_INVALID");
}
function challenge(error: string, headers: Record<string, string> = {}): Response {
return new Response(null, {
status: 401,
headers: { ...headers, "www-authenticate": `DPoP error="${error}", algs="ES256 EdDSA"` },
});
}- Token first:
verifyDPoPProofdoesn't validate the access token. Acnf.jktyou read from a token you haven't verified binds nothing. accessToken: { token, thumbprint }: checks both links at once: the proof'sathis this token's hash, and the proof is signed by the keycnf.jktnames. Leave it out only at the token endpoint.algorithms: required, the asymmetric algorithms you accept. A proof signed with anything else fails.maxTokenAge: required, in seconds, measured from the proof'siat. Keep it short; a minute is common.clockToleranceadds seconds on both sides,0by default.nonce: when set, a proof without that exact nonce fails withERR_DPOP_NONCE_INVALID, checked after everything else. Without it, a nonce in the proof is only checked for its form.- Exactly one proof: a request with two
DPoPheaders reads as one value joined by a comma, and a proof never contains one, soincludes(",")catches it. - Same URL, normalized: the proof's URL is compared without its query and fragment, ignoring scheme and host case and a default port. The method is compared exactly:
postisn'tPOST.
#Issue nonces
A nonce lets the server decide how fresh a proof must be, instead of trusting the client's clock. One nonce for everyone, replaced every few minutes, is enough for most APIs:
const NONCE_LIFETIME_MS = 5 * 60_000;
let nonce = { value: newNonce(), issuedAt: Date.now() };
/** The nonce proofs must carry; replaced every five minutes. */
export function currentNonce(now = Date.now()) {
if (now - nonce.issuedAt >= NONCE_LIFETIME_MS) nonce = { value: newNonce(), issuedAt: now };
return nonce.value;
}
function newNonce(): string {
return base64UrlStringify(secureRandomBytes(16));
}When the nonce rotates, a client still sending the old one gets use_dpop_nonce with the new value and retries, as the client above does. With several servers, every server must hand out and expect the same nonce.
#Refuse a replayed proof
A captured proof stays valid until its age runs out. Pass consumeProof to accept each proof once:
// One process only: several servers need a shared store with an atomic insert.
const seen = new Map<string, number>();
/** Accepts each proof once, per key, for as long as its `iat` keeps it acceptable. */
export async function consumeOnce({ payload, thumbprint }: DPoPVerifyResult) {
const id = await hash(`${thumbprint}.${payload.jti}`);
const now = Math.floor(Date.now() / 1000);
for (const [key, expiresAt] of seen) if (expiresAt < now) seen.delete(key);
if (seen.has(id)) return false;
seen.set(id, payload.iat + MAX_AGE + TOLERANCE);
return true;
}- Runs last:
verifyDPoPProofcalls it only after every other check passed, so a forged or stale proof never fills your store. - Only
trueaccepts:false, any other value, or a throw rejects the proof withERR_DPOP_REPLAY. A throw keeps your error ascause, so you can tell a store outage from a replay. - Check and insert at once: two requests with the same proof can arrive together. In one process the check and the insert above run without a pause between them; across servers, use a store with an atomic insert-if-absent.
- Keep it long enough: a proof is acceptable until
iat + maxTokenAge + clockTolerance, so keep each record that long. - Bounded keys:
jticomes from the client and can be any length, so the key is a digest of thumbprint andjti.
#What stays with you
- HTTP: reading the
Authorization: DPoPandDPoPheaders, refusing a request with more than one proof, and theWWW-AuthenticateandDPoP-Nonceresponses. - The access token: its signature, expiry, audience and scopes, and reading
cnf.jktfrom it. - Nonces: issuing, rotating and sharing them.
- Replay storage: the store behind
consumeProof. - HTTPS: a proof protects the token, not the connection.
#When it fails
| Situation | What happens |
|---|---|
The proof is malformed, signed with an algorithm outside algorithms, carries a bad key or a bad signature | ERR_DPOP_INVALID, with the core error as cause. Answer invalid_dpop_proof. |
Wrong method or URL, too old or from the future, past its exp or before its nbf, or bound to another token or key | ERR_DPOP_CLAIM_INVALID. Answer invalid_dpop_proof. |
| The nonce you expect is missing or different | ERR_DPOP_NONCE_INVALID. Answer use_dpop_nonce with a new DPoP-Nonce. |
consumeProof returned anything but true | ERR_DPOP_REPLAY without cause. Answer invalid_dpop_proof. |
consumeProof threw | ERR_DPOP_REPLAY with your error as cause. Answer with a 5xx. |
An empty algorithms, a maxTokenAge that isn't positive seconds, an accessToken without its thumbprint | ERR_INVALID_OPTION: fix the call. |
createDPoPProof with a symmetric key, a CryptoKeyPair without algorithm, or an ambiguous key | ERR_INVALID_OPTION. |
Handle errors lists the DPoP codes with the rest.
#Options
createDPoPProof(target, options):
| Option | Default | Notes |
|---|---|---|
keyPair | required | A JWK pair or a CryptoKeyPair, asymmetric. |
algorithm | inferred | Required for a CryptoKeyPair and for keys with more than one answer. |
jti | a fresh UUID v4 | Unique per proof. |
iat | the current second | NumericDate, in seconds. |
exp, nbf | not written | Absolute times in seconds. |
nonce | not written | The server's latest DPoP-Nonce. |
accessToken | not written | { token }: adds the token's hash as ath. |
verifyDPoPProof(proof, target, options):
| Option | Default | Notes |
|---|---|---|
algorithms | required | Asymmetric signing algorithms you accept. |
maxTokenAge | required | Positive number of seconds since iat. |
clockTolerance | 0 | Seconds allowed on either side. |
currentDate | now | The clock, for tests. |
nonce | none | The nonce the proof must carry. |
accessToken | none | { token, thumbprint }: the presented token and its verified cnf.jkt. |
consumeProof | none | A function of the result that returns true, or a promise of it, to accept the proof. Runs after every other check. |
#Going further
- Thumbprints: Import and export keys covers
thumbprint(), the valuecnf.jktholds. - Claims in the access token: Validate claims covers the checks the access token needs before its
cnf.jktmeans anything. - The specification: RFC 9449 §7 describes the protected-resource side, §8 and §9 the nonces.