Skip to main content

Bind tokens to a key with DPoP

Make a stolen token useless: the client proves, at each request, that it holds the key that the token is bound to.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGo
Standards
RFC 9449

What it shows​

  1. The service "Ledger sync" creates a key pair and sends a DPoP proof with its token request. The token comes back with token_type: DPoP.
  2. The token carries the thumbprint of the public key in the claim cnf.jkt.
  3. Each call to the Ledger API carries a new proof, signed with the key and bound to the token.
  4. The API verifies the token, the proof, the binding, and that the proof was not used before.
  5. The API asks for a nonce with use_dpop_nonce. The client signs a new proof with the nonce and sends the request again.

Someone who copies the token, or a whole request, cannot use it: the private key never leaves the client.

Before you start​

  • An API key for the setup script, with the scopes admin:permissions:read, admin:permissions:write, admin:clients:read and admin:clients:write.
  • A confidential application with the client credentials grant. The setup script creates the application "Ledger sync" and the scope ledger:read.
  • A free local port for the Ledger API. The default is 4000.

Any application can ask for a DPoP-bound token: the proof in the token request is enough.

VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
CLIENT_IDThe client ID of the application. The setup script prints it.
CLIENT_SECRETThe secret of the application. The setup script prints it once, when it creates the application.
PORTOptional. The local port of the Ledger API. The default is 4000.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node oauth/dpop/setup.mjs
setup.mjs
// Creates what the recipe needs: the scope of the Ledger API, and the
// confidential application "Ledger sync", a service that calls that API.
// Run it again at any time. The client secret is shown once, when the
// application is created: add --new-secret to replace a secret that you lost.
//
// node oauth/dpop/setup.mjs
//
// The API key needs the scopes admin:permissions:read, admin:permissions:write,
// admin:clients:read and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';

await ensure('/admin/scopes', (s) => s.name === 'ledger:read', { name: 'ledger:read', description: 'Read the balances of the ledger.' });

const name = 'Ledger sync';
let client = (await list('/admin/clients')).find((c) => c.name === name);
let secret;
if (!client) {
const created = await call('POST', '/admin/clients', {
name,
isConfidential: true,
grantTypes: ['client_credentials'],
scopes: ['ledger:read'],
});
client = created.data;
secret = client.secret;
} else if (process.argv.includes('--new-secret')) {
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
}

console.log(`The application "${name}" is ready.`);
printEnv({ CLIENT_ID: client.clientId, ...(secret ? { CLIENT_SECRET: secret } : {}) });
if (!secret) console.log('# CLIENT_SECRET was printed when the application was created. Add --new-secret to get a new one.');

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. In each language the first file is the client. It starts the Ledger API of the second file on a local port. The programs were also run against an organization that requires nonces at the token endpoint: the token request then takes two requests too.

oauth/dpop/js/client.mjs
// Starts the Ledger API, gets a token that is bound to a key, and calls the
// API with it. Then it plays a thief: a copied request and a stolen token.
//
// node oauth/dpop/js/client.mjs
import { DpopProofSigner, decodeJwt, fetchWithDpop, issuerFor } from '@lumoauth/agent';
import { api } from './api.mjs';

const port = process.env.PORT ?? 4000;
api.listen(port);
const ledger = `http://localhost:${port}/balance`;
const issuer = issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID);

// 1. The client makes a key pair. The private key never leaves the client.
const signer = DpopProofSigner.generate();

// 2. The token request carries a proof. fetchWithDpop adds it, and answers
// a use_dpop_nonce once if the organization asks for nonces. It sends no
// Authorization header of its own caller, so the secret is in the body.
const response = await fetchWithDpop(fetch, `${issuer}/oauth/token`, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
scope: 'ledger:read',
resource: 'https://ledger.example.com',
}),
}, signer);
if (!response.ok) throw new Error(await response.text());
const { access_token: token, token_type: tokenType } = await response.json();
// The token names the key by its thumbprint, in the claim cnf.jkt.
const bound = decodeJwt(token).claims.cnf?.jkt === signer.thumbprint;
console.log(`token: ${tokenType}, bound to this key: ${bound ? 'yes' : 'no'}`);

// 3. Each call carries a new proof with the hash of the token. The API asks
// for a nonce first, and fetchWithDpop sends the request again with it.
let requests = 0;
const counting = (url, init) => {
requests++;
return fetch(url, init);
};
const balance = await fetchWithDpop(counting, ledger, { method: 'GET' }, signer, { accessToken: token });
console.log(`API: ${balance.status} after ${requests} requests, the first one got use_dpop_nonce`);

// 4. A proof works once: whoever copies the request cannot send it again.
const copied = { Authorization: `DPoP ${token}`, DPoP: signer.createProof({ method: 'GET', url: ledger, accessToken: token }) };
const first = await fetch(ledger, { headers: copied });
const again = await fetch(ledger, { headers: copied });
console.log(`the same request twice: ${first.status}, then ${again.status} ${(await again.json()).error}`);

// 5. A stolen token is of no use without the private key.
const thief = DpopProofSigner.generate();
const proof = thief.createProof({ method: 'GET', url: ledger, accessToken: token, nonce: signer.getNonce(ledger) });
const stolen = await fetch(ledger, { headers: { Authorization: `DPoP ${token}`, DPoP: proof } });
console.log(`the token with a proof of another key: ${stolen.status} ${(await stolen.json()).error}`);
const bearer = await fetch(ledger, { headers: { Authorization: `Bearer ${token}` } });
console.log(`the token without a proof: ${bearer.status} ${(await bearer.json()).error}`);

api.close();
oauth/dpop/js/api.mjs
// The Ledger API. It accepts only tokens that are bound to a key: each
// request carries a new DPoP proof, signed with the key of the token.
import { randomBytes } from 'node:crypto';
import http from 'node:http';
import { AccessTokenError, createAccessTokenVerifier, decodeJwt, issuerFor } from '@lumoauth/agent';

const verifier = createAccessTokenVerifier({
issuer: issuerFor(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev', process.env.LUMOAUTH_ORG_ID),
resource: 'https://ledger.example.com',
// A valid token that is not bound to a key is refused too.
requireDpop: true,
});

// The API hands out a nonce, so that a proof made in advance is of no use.
// A real API changes the value every few minutes.
const nonce = randomBytes(16).toString('base64url');

function refuse(response, error, description) {
const headers = { 'Content-Type': 'application/json', 'WWW-Authenticate': `DPoP error="${error}"` };
if (error === 'use_dpop_nonce') headers['DPoP-Nonce'] = nonce;
response.writeHead(401, headers).end(JSON.stringify({ error, error_description: description }));
}

export const api = http.createServer(async (request, response) => {
// A proof without the current nonce gets the nonce, and the client tries again.
const proof = request.headers.dpop;
let sentNonce;
try {
sentNonce = proof ? decodeJwt(proof).claims.nonce : undefined;
} catch {}
if (proof && sentNonce !== nonce) return refuse(response, 'use_dpop_nonce', 'Send a new proof with this nonce.');

try {
// The verifier checks the token, the proof, the binding of the token to
// the key of the proof, and that the proof was not used before.
const url = `http://${request.headers.host}${request.url}`;
const claims = await verifier.verifyRequest({ method: request.method, url, headers: request.headers, nonce });
response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ balance: 1250, client: claims.client_id }));
} catch (error) {
if (!(error instanceof AccessTokenError)) throw error;
refuse(response, error.code, error.message);
}
});
node oauth/dpop/js/client.mjs

The SDKs sign the proofs, verify the tokens and keep the nonces. The token requests are plain POSTs with the SDK's proof, because they send resource, the identifier of the Ledger API. The SDK calls for client credentials in Python and Go have no parameter for it.

Check the result​

Output
token: DPoP, bound to this key: yes
API: 200 after 2 requests, the first one got use_dpop_nonce
the same request twice: 200, then 401 invalid_dpop_proof
the token with a proof of another key: 401 invalid_dpop_proof
the token without a proof: 401 invalid_token
  • The first call takes two requests: the API answers the first one with 401, WWW-Authenticate: DPoP error="use_dpop_nonce" and a DPoP-Nonce header.
  • The thief in the program has the token and the nonce, but signs with another key. The API refuses the proof, because its key does not match cnf.jkt.
  • To refuse token requests without a proof, open Applications & developer tools, Applications, Ledger sync in the portal, then the Security tab. Under FAPI 2.0 and client authentication, turn on Require DPoP and select Save FAPI settings. A token request without a proof then answers 400 invalid_dpop_proof.

Limits​

  • A proof covers the method, the address without the query, and the hash of the token. It does not cover the body of the request.
  • The verifiers remember the IDs of proofs in memory, for one process. An API with several instances needs a shared cache: pass your own with replayCache (Node.js), replay_cache (Python) or ReplayCache (Go).
  • The Go verifier has no option for an expected nonce, so the Go API reads the nonce claim of the proof itself. The SDK still verifies the signature of the proof.
  • fetchWithDpop sends no Authorization header of its caller. On a token request, put the client ID and secret in the body.
  • Your organization can also require a nonce at the token endpoint. The token request then answers 400 use_dpop_nonce first, and the same retry handles it. See server-provided nonces.