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.
What it shows
- 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. - The token carries the thumbprint of the public key in the claim
cnf.jkt. - Each call to the Ledger API carries a new proof, signed with the key and bound to the token.
- The API verifies the token, the proof, the binding, and that the proof was not used before.
- 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:readandadmin: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.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
CLIENT_ID | The client ID of the application. The setup script prints it. |
CLIENT_SECRET | The secret of the application. The setup script prints it once, when it creates the application. |
PORT | Optional. 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.
- Node.js
- Python
- Go
// 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();
// 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
"""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.
python oauth/dpop/python/client.py
"""
import os
import threading
from http.server import ThreadingHTTPServer
import jwt
import requests
from lumoauth import DpopProofSigner, LumoAuth
from lumoauth.dpop import wants_new_nonce
from api import LedgerApi
port = int(os.environ.get("PORT", "4000"))
server = ThreadingHTTPServer(("localhost", port), LedgerApi)
threading.Thread(target=server.serve_forever, daemon=True).start()
ledger = f"http://localhost:{port}/balance"
token_url = f"{LumoAuth().issuer}/oauth/token"
# 1. The client makes a key pair. The private key never leaves the client.
signer = DpopProofSigner()
def send(method, url, token=None, **options):
"""Sends a request with a new proof, and once more when the server asks for a nonce."""
for attempt in (1, 2):
response = requests.request(method, url, headers=signer.headers(method, url, token), **options)
signer.observe_response(url, response.headers)
body = response.json() if response.content else None
if attempt == 2 or not wants_new_nonce(response.status_code, response.headers, body):
return response, attempt
# 2. The token request carries a proof. The SDK call for client credentials
# has no `resource`, so the request is a plain POST with the SDK's proof.
response, _ = send(
"POST",
token_url,
data={
"grant_type": "client_credentials",
"client_id": os.environ["CLIENT_ID"],
"client_secret": os.environ["CLIENT_SECRET"],
"scope": "ledger:read",
"resource": "https://ledger.example.com",
},
)
response.raise_for_status()
token = response.json()["access_token"]
# The token names the key by its thumbprint, in the claim cnf.jkt.
bound = jwt.decode(token, options={"verify_signature": False}).get("cnf", {}).get("jkt") == signer.thumbprint
print(f"token: {response.json()['token_type']}, bound to this key: {'yes' if bound else 'no'}")
# 3. Each call carries a new proof with the hash of the token. The API asks
# for a nonce first, and send() tries again with it.
balance, requests_sent = send("GET", ledger, token)
print(f"API: {balance.status_code} after {requests_sent} requests, the first one got use_dpop_nonce")
# 4. A proof works once: whoever copies the request cannot send it again.
copied = signer.headers("GET", ledger, token)
first = requests.get(ledger, headers=copied)
again = requests.get(ledger, headers=copied)
print(f"the same request twice: {first.status_code}, then {again.status_code} {again.json()['error']}")
# 5. A stolen token is of no use without the private key.
thief = DpopProofSigner()
stolen = requests.get(ledger, headers=thief.headers("GET", ledger, token, nonce=signer.nonce_for(ledger)))
print(f"the token with a proof of another key: {stolen.status_code} {stolen.json()['error']}")
bearer = requests.get(ledger, headers={"Authorization": f"Bearer {token}"})
print(f"the token without a proof: {bearer.status_code} {bearer.json()['error']}")
server.shutdown()
"""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 json
import secrets
from http.server import BaseHTTPRequestHandler
from lumoauth import AccessTokenVerifier, DpopRequest, LumoAuth, LumoAuthTokenError
verifier = AccessTokenVerifier(
LumoAuth().issuer, # from LUMOAUTH_URL and LUMOAUTH_ORG_ID
"https://ledger.example.com",
# A valid token that is not bound to a key is refused too.
require_dpop=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.
nonce = secrets.token_urlsafe(16)
class LedgerApi(BaseHTTPRequestHandler):
def do_GET(self):
scheme, _, token = (self.headers.get("Authorization") or "").partition(" ")
request = DpopRequest(
method="GET",
url=f"http://{self.headers['Host']}{self.path}",
proof=self.headers.get("DPoP"),
scheme=scheme,
nonce=nonce,
)
try:
# The verifier checks the token, the proof, the binding of the
# token to the key of the proof, and that the proof is new.
claims = verifier.verify(token, dpop=request)
except LumoAuthTokenError as error:
# A proof without the current nonce gets the nonce, and the client tries again.
if error.code == "DPOP_USE_NONCE":
return self.answer(401, {"error": "use_dpop_nonce"}, 'DPoP error="use_dpop_nonce"', nonce)
return self.answer(401, {"error": error.error, "error_description": error.message}, error.www_authenticate)
self.answer(200, {"balance": 1250, "client": claims.client_id})
def answer(self, status, body, challenge=None, new_nonce=None):
self.send_response(status)
self.send_header("Content-Type", "application/json")
if challenge:
self.send_header("WWW-Authenticate", challenge)
if new_nonce:
self.send_header("DPoP-Nonce", new_nonce)
self.end_headers()
self.wfile.write(json.dumps(body).encode())
def log_message(self, *args):
pass
python oauth/dpop/python/client.py
// 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.
//
// go run ./oauth/dpop/go
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
issuer := os.Getenv("LUMOAUTH_URL") + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
port := os.Getenv("PORT")
if port == "" {
port = "4000"
}
listener, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatal(err)
}
go http.Serve(listener, newLedgerAPI(issuer))
ledger := "http://localhost:" + port + "/balance"
// 1. The client makes a key pair. The private key never leaves the client.
signer, err := lumoauth.NewDPoPSigner()
if err != nil {
log.Fatal(err)
}
// send makes a request with a new proof. A refusal with a DPoP-Nonce
// header asks for a nonce: RememberNonce stores it, and the request
// goes once more with a new proof.
send := func(build func() *http.Request) (*http.Response, int) {
response := do(build())
if response.StatusCode >= 400 && signer.RememberNonce(response) {
response.Body.Close()
return do(build()), 2
}
return response, 1
}
// 2. The token request carries a proof. The SDK call for client
// credentials has no `resource`, so the request is a plain POST with
// the SDK's proof.
form := url.Values{
"grant_type": {"client_credentials"},
"client_id": {os.Getenv("CLIENT_ID")},
"client_secret": {os.Getenv("CLIENT_SECRET")},
"scope": {"ledger:read"},
"resource": {"https://ledger.example.com"},
}
response, _ := send(func() *http.Request {
request, _ := http.NewRequest("POST", issuer+"/oauth/token", strings.NewReader(form.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
proof, err := signer.Proof("POST", issuer+"/oauth/token")
if err != nil {
log.Fatal(err)
}
request.Header.Set(lumoauth.DPoPHeader, proof)
return request
})
var tokens struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}
json.NewDecoder(response.Body).Decode(&tokens)
if tokens.AccessToken == "" {
log.Fatalf("The token request failed: %s", response.Status)
}
token := tokens.AccessToken
// The token names the key by its thumbprint, in the claim cnf.jkt.
var claims struct {
Cnf struct {
JKT string `json:"jkt"`
} `json:"cnf"`
}
jwtPayload(token, &claims)
fmt.Printf("token: %s, bound to this key: %s\n", tokens.TokenType, yesNo(claims.Cnf.JKT == signer.Thumbprint()))
// 3. Each call carries a new proof with the hash of the token. The API
// asks for a nonce first, and send() tries again with it.
call := func() *http.Request {
request, _ := http.NewRequest("GET", ledger, nil)
if err := signer.AuthorizeRequest(request, token); err != nil {
log.Fatal(err)
}
return request
}
balance, attempts := send(call)
fmt.Printf("API: %d after %d requests, the first one got use_dpop_nonce\n", balance.StatusCode, attempts)
// 4. A proof works once: whoever copies the request cannot send it again.
copied := call()
first := do(copied)
again := do(copied.Clone(copied.Context()))
fmt.Printf("the same request twice: %d, then %d %s\n", first.StatusCode, again.StatusCode, errorOf(again))
// 5. A stolen token is of no use without the private key.
thief, _ := lumoauth.NewDPoPSigner()
thief.SetNonce(ledger, signer.Nonce(ledger))
stolen, _ := http.NewRequest("GET", ledger, nil)
thief.AuthorizeRequest(stolen, token)
answer := do(stolen)
fmt.Printf("the token with a proof of another key: %d %s\n", answer.StatusCode, errorOf(answer))
bearer, _ := http.NewRequest("GET", ledger, nil)
bearer.Header.Set("Authorization", "Bearer "+token)
answer = do(bearer)
fmt.Printf("the token without a proof: %d %s\n", answer.StatusCode, errorOf(answer))
}
func do(request *http.Request) *http.Response {
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
return response
}
// errorOf reads the `error` of a refusal.
func errorOf(response *http.Response) string {
defer response.Body.Close()
var body struct {
Error string `json:"error"`
}
json.NewDecoder(response.Body).Decode(&body)
return body.Error
}
func yesNo(value bool) string {
if value {
return "yes"
}
return "no"
}
// 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.
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"net/http"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
// 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.
var nonce = func() string {
bytes := make([]byte, 16)
rand.Read(bytes)
return base64.RawURLEncoding.EncodeToString(bytes)
}()
func newLedgerAPI(issuer string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// A proof without the current nonce gets the nonce, and the client
// tries again. The SDK has no nonce option, so the API reads the
// claim itself; the verification below checks the signature.
proof := r.Header.Get(lumoauth.DPoPHeader)
if proof != "" && proofNonce(proof) != nonce {
w.Header().Set(lumoauth.DPoPNonceHeader, nonce)
refuse(w, "use_dpop_nonce", "Send a new proof with this nonce.")
return
}
// 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.
_, token, _ := strings.Cut(r.Header.Get("Authorization"), " ")
claims, err := lumoauth.VerifyAccessToken(r.Context(), token, lumoauth.AccessTokenVerifyOptions{
Issuer: issuer,
Resource: "https://ledger.example.com",
// A valid token that is not bound to a key is refused too.
RequireDPoP: true,
DPoP: lumoauth.DPoPRequestFromHTTP(r),
})
if err != nil {
switch lumoauth.RejectionReason(err) {
case lumoauth.TokenRejectedDPoPProof, lumoauth.TokenRejectedDPoPBinding, lumoauth.TokenRejectedDPoPReplay:
refuse(w, "invalid_dpop_proof", err.Error())
default:
refuse(w, "invalid_token", err.Error())
}
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"balance": 1250, "client": claims.ClientID})
})
}
func refuse(w http.ResponseWriter, code, description string) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("WWW-Authenticate", `DPoP error="`+code+`"`)
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": code, "error_description": description})
}
// proofNonce reads the nonce claim of a proof, without verifying it.
func proofNonce(proof string) string {
var claims struct {
Nonce string `json:"nonce"`
}
jwtPayload(proof, &claims)
return claims.Nonce
}
// jwtPayload decodes the claims of a JWT WITHOUT verifying its signature.
func jwtPayload(token string, into any) {
parts := strings.Split(token, ".")
if len(parts) == 3 {
payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
json.Unmarshal(payload, into)
}
}
go run ./oauth/dpop/go
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
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 aDPoP-Nonceheader. - 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) orReplayCache(Go). - The Go verifier has no option for an expected nonce, so the Go API reads the
nonceclaim of the proof itself. The SDK still verifies the signature of the proof. fetchWithDpopsends noAuthorizationheader 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_noncefirst, and the same retry handles it. See server-provided nonces.