Skip to content

About

DPoP proof JWTs for Dart (RFC 9449) — ES256 key handling, PEM storage, JWK thumbprints, access-token binding and server-supplied nonces.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

dpop_client

pub package pub points CI license: AGPL-3.0 Dart last commit live demo

DPoP proof JWTs for Dart, as specified by RFC 9449 — ES256 key handling, PEM and JWK storage, JWK thumbprints, access-token binding and server-supplied nonces.

Pure Dart, so it works in Flutter apps, server code and CLIs alike. Try it in the browser at ctrlaltdevelop.github.io/dpop_client.

final keyPair = DPoPKeyPair.generate();
await secureStorage.write('dpop_key', keyPair.privateKeyPem);

final proof = DPoPClient(keyPair).createProof(
  url: Uri.parse('https://api.example.com/v1/orders?limit=20'),
  method: 'POST',
  accessToken: accessToken,
);

// {'DPoP': 'eyJ0eXAiOiJkcG9w…', 'Authorization': 'DPoP <access token>'}
request.headers.addAll(proof.headers());

Why

A bearer token is a password: whoever holds it is the user. DPoP fixes that by binding the token to a key pair the client generates and never sends. Every request carries a short-lived JWT — the proof — signed by that key and covering the request's method and URI, so a token lifted from a log or a proxy is inert without the private key alongside it.

The mechanics are small but unforgiving. Get the htu normalisation, the ath hash or the iat truncation slightly wrong and the server rejects every request with a message that names none of them. This package is those details.

Install

dependencies:
  dpop_client: ">=2.4.0 <3.0.0"

Requires Dart 3.12.0 or newer, and so any Flutter release shipping that SDK or later — Flutter 3.44.0 and up. There is no flutter constraint in pubspec.yaml, so the package still resolves in server and CLI projects with no Flutter SDK installed.

Keys

DPoPKeyPair wraps an ES256 (P-256) pair — the pairing authorization servers actually implement, and the only one this package supports.

final keyPair = DPoPKeyPair.generate();

Persist privateKeyPem and nothing else: the public half is derived from the private scalar on restore.

final keyPair = DPoPKeyPair.fromPrivateKeyPem(await storage.read('dpop_key'));

Both PEM forms are accepted: the SEC 1 EC PRIVATE KEY block this package emits, and the PKCS#8 PRIVATE KEY block most other tooling produces. A key on any curve but P-256 is refused outright rather than reinterpreted.

Or as a JWK

Storage that holds JSON rather than PEM — and anything that has to interoperate with WebCrypto or a JOSE library elsewhere — can keep the key as a JWK instead:

await storage.write('dpop_key', jsonEncode(keyPair.privateJwk));

final keyPair = DPoPKeyPair.fromPrivateJwk(
  jsonDecode(await storage.read('dpop_key')) as Map<String, dynamic>,
);

privateJwk is the public jwk plus d, so the two forms are the same key — fromPrivateJwk and fromPrivateKeyPem give byte-identical proofs. It is what crypto.subtle.exportKey('jwk', …) produces, and fromPrivateJwk reads a WebCrypto export as it arrives: only kty, crv, d, x and y are looked at, so ext and key_ops can stay on it.

x and y are optional, since the public half is derived from d, and checked when they are there — a JWK whose coordinates do not belong to its d is refused rather than used to publish a key that cannot verify its own signatures.

privateJwk carries the private key: it belongs in the keystore with privateKeyPem, never in a log or a header. jwk is the publishable one, and dpopThumbprint refuses anything carrying d for exactly that reason.

The private key is the client's identity for every token bound to it. Keep it in the platform keystore — flutter_secure_storage, the Keychain, the Android keystore — not in plain preferences, and generate a fresh pair on sign-out so the old one cannot be used to keep presenting an old token.

Thumbprints

thumbprint is the key's RFC 7638 SHA-256 JWK thumbprint — the jkt an authorization server records against a DPoP-bound access token. Compare it against the token's cnf.jkt claim to confirm a token you have been issued is bound to the key you hold, which is worth doing after restoring a key from storage:

if (decodedToken['cnf']?['jkt'] != keyPair.thumbprint) {
  // This token belongs to a key we no longer have. Re-authenticate.
}

Proofs

One proof per request. They are bound to a method, a URI and a moment, so caching one is never right.

final client = DPoPClient(keyPair);

final proof = client.createProof(
  url: Uri.parse('https://api.example.com/v1/orders?limit=20'),
  method: 'POST',
  accessToken: accessToken,
);
Claim Set from Notes
htm method Upper-cased.
htu url Query, fragment and userinfo are dropped, per RFC 9449 §4.2. An empty path becomes /.
iat now Truncated to whole seconds, never rounded up.
jti UUID v4 Fresh per proof, so a server's replay cache never collides.
ath accessToken Unpadded base64url SHA-256 of the token. Omitted when no token is passed.
nonce nonce Omitted when null or empty.

The public JWK travels in the JWT header, alongside typ: dpop+jwt and alg: ES256.

Pass the URL as you will send it

htu carries no query string. Hand createProof the full URL and let it normalise — do not trim at the call site, and do not assume your HTTP client gives you a clean one. This is the single most common way a DPoP integration fails, because a query parameter added by an interceptor (a ?lang= on every request, say) is invisible at the point the proof is built.

Rebuilding the URI also applies the normalisations the server will have applied to its own copy:

  • a redundantly-stated default port is dropped, so https://api.example.com:443/x and https://api.example.com/x agree;
  • userinfo is dropped — a target URI has no userinfo component, so leaving it in both guarantees a mismatch and writes any password in the URL into a JWT payload the server is free to log;
  • an empty path becomes / — RFC 9110 §7.1 has the client send / when the path is empty, so https://api.example.com is reconstructed server-side as https://api.example.com/.

Send the token under the DPoP scheme, not Bearer

A DPoP-bound access token is presented with Authorization: DPoP <token>, not Authorization: Bearer <token> (RFC 9449 §7.1). A perfectly good proof sent alongside a Bearer header is still rejected, and this is the step integrations miss most often — the proof looks right, so the header rarely gets a second look.

headers() emits both, so there is nothing to remember:

final proof = client.createProof(
  url: url,
  method: 'POST',
  accessToken: accessToken,
);

request.headers.addAll(proof.headers());
// {'DPoP': 'eyJ0eXAiOiJkcG9w…', 'Authorization': 'DPoP <access token>'}

The token comes from the proof itself rather than a second argument, so the Authorization header can never disagree with the ath claim. Create a proof without an access token — the token request itself — and no Authorization header is produced, matching the absent ath.

Nonces

A server that wants a nonce answers 401 with error="use_dpop_nonce" and a DPoP-Nonce response header. Retry with that value, and keep using the most recent one the server sent until it issues another — which it may do on any response, including a successful one (RFC 9449 §8).

DPoPNonceStore holds that state. Give one to the client and every proof carries the right nonce for the server it is going to:

final nonces = DPoPNonceStore();
final client = DPoPClient(keyPair, nonces: nonces);

Future<Response> send(Request request) async {
  final proof = client.createProof(url: request.url, method: request.method);
  final response = await _send(request, proof);

  // `update` returns true only for a nonce this store had not already tried,
  // which is both the reason to retry and the guard against retrying forever.
  if (nonces.update(request.url, response.headers) &&
      response.statusCode == 401) {
    return send(request);
  }
  return response;
}

Nonces are kept per origin — scheme, host and port — because that is the granularity the RFC gives them: an authorization server and a resource server run separate nonce spaces, and offering one server's nonce to another earns a fresh 401 at best. Header names are matched case-insensitively, so a map from dart:io, package:http or a gateway SDK all work.

Passing nonce: to createProof still overrides the store, forget(url) drops one origin — worth doing when a server rejects a proof for some other reason — and clear() empties it on sign-out. The store is memory only: a nonce is short-lived and server-issued, so losing the lot on restart costs one round trip and nothing else.

Keys you cannot read

DPoPKeyPair holds the private key in Dart memory. If your key lives where script and Dart code must not read it — a WebCrypto CryptoKey created with extractable: false, the Android Keystore, the iOS Keychain — implement DPoPSigner over it and use DPoPSignerClient. Signing there is async, so createProof returns a Future; everything else, including claims and headers(), is the same.

class WebCryptoSigner implements DPoPSigner {
  @override
  final Map<String, String> publicJwk; // kty, crv, x, y — public members only

  @override
  Future<Uint8List> sign(Uint8List message) async {
    // Must return the raw 64 byte r || s, which is what WebCrypto's ECDSA
    // already gives. A DER signature is rejected with a StateError.
    return signWithKeystore(message);
  }
}

final client = DPoPSignerClient(WebCryptoSigner(...));
final proof = await client.createProof(url: url, method: 'GET');

Limit publicJwk to exactly kty, crv, x and y. It is published as-is in every proof's header, and a WebCrypto export also carries ext and key_ops, which would travel with every request. They do no harm to the thumbprint, which ignores them, but a proof has no use for them. Copy the four members out of the exported JWK rather than passing it through.

dpopThumbprint(jwk) gives the key's jkt from the public JWK alone, for the moment before any proof exists (client.thumbprint is the same value). createProof accepts ws and wss URLs too, for a WebSocket handshake, and drops their default ports (wss:443, ws:80).

Checking a token is bound to your key

A JWT access token carries the key it is bound to in cnf.jkt. After restoring a key or refreshing a token, isBoundTo tells you whether the two still agree:

switch (keyPair.isBoundTo(accessToken)) {
  case true:  // bound to this key
  case false: // bound to another key — sign in again
  case null:  // opaque token; introspect it to find out
}

The token is read, not verified — this catches a stale key, it is not a trust decision.

Non-standard header names

RFC 9449 specifies the DPoP header. If your gateway wants something else, name it:

request.headers.addAll(proof.headers(name: 'X-DPOP'));

Some gateways also want the JWK in a header of its own, even though the proof already carries it. keyPair.jwkJson is that value.

Three details this package gets right

Each is easy to get wrong by hand, and none produces a diagnosable error when you do.

iat is truncated, not rounded. Rounding pushes the timestamp up to half a second into the future, which a server with no clock-skew allowance rejects. A hand-rolled signer built on dart_jsonwebtoken also has to pass noIssueAt: true, since the library otherwise overwrites iat with its own clock on the way out — so code that computes iat carefully often finds the value never reaches the token.

htu excludes the query, the fragment and the userinfo, and never has an empty path. See above.

The bound token is sent under the DPoP scheme. See above.

Speed

A proof costs one ES256 signature, and an ES256 signature costs one scalar multiplication of the curve's generator. Two things make that cheap here, and neither changes what a signature is:

  • Jacobian coordinates. pointycastle holds points in affine form, where every addition and doubling divides — a modular inverse each, roughly fifty times the cost of a multiplication, some 340 of them per signature. The ladder here runs on multiplications and divides once, at the end.
  • A fixed-base comb. The generator never changes, so its multiples are precomputed: k * G costs 32 doublings and 32 additions rather than 256 and 64.

~0.23 ms per proof on the Dart VM, down from ~2.8 ms — about eleven times faster. Key generation and fromPrivateKeyPem multiply too, and got the same.

The table that makes it work is 255 points, built on the first signature: about 15 ms once, and roughly 35 KB held for the life of the process. A process that signs a single proof and exits is therefore slower than it was; everything that stays signed in is far faster.

ECDSASigner still derives k (RFC 6979) and computes r and s; only the multiplication is this package's, and the tests check it against pointycastle's own answer for 250 random scalars, for every single-bit scalar in all 256 positions, at the comb's row boundaries and against the curve equation. Signatures are byte-for-byte unchanged.

Two things follow from this. Hold one DPoPClient and one DPoPKeyPair for the session — every derived value, from the PEMs to the thumbprint, is computed once and cached on the key pair. And on the web, where BigInt runs an order of magnitude slower than on the VM, prefer a WebCrypto key behind a DPoPSigner: it is both faster and unextractable.

Like pointycastle — and like Dart's BigInt underneath it — none of this is constant-time. That is the exposure the package always had, and it is the other reason a key that must resist a local side-channel attacker belongs in a platform keystore rather than in Dart memory.

Verifying a proof

This package signs proofs; it does not verify them, because a resource server needs replay detection, nonce issuance and clock-skew policy that belong with the server, not a client library. If you are writing a verifier, note that dart_jsonwebtoken's JWT.verify rejects a proof outright unless you pass checkHeaderType: false — a DPoP proof is typed dpop+jwt, not JWT.

Scope

  • ES256 over P-256 only. RFC 9449 permits other algorithms; servers rarely do. A key on another curve is refused, not reinterpreted.
  • Signing only. No verification, and no HTTP client — DPoPNonceStore reads a header map you hand it and never sends anything itself.
  • No key storage. Persist privateKeyPem or privateJwk with whatever your platform offers, or keep the key in a keystore and sign through a DPoPSigner.

The dependency footprint is deliberately small — pointycastle and asn1lib for the curve and the PEMs, dart_jsonwebtoken for the ES256 signature, crypto and uuid. Nothing here pulls in an HTTP client or a logger.

The demo

ctrlaltdevelop.github.io/dpop_client is this package compiled to JavaScript: generate a key, describe a request, and read the proof's claims the way a server would. Nothing is mocked and nothing leaves the browser. Its source is example/web, and example/dpop_client_example.dart is the same walk-through on the command line.

Upgrading from 1.x

headers() now also returns the Authorization header when the proof carries an access token. If you were setting that header yourself, drop your own line — and if you were setting it to Bearer, that was the bug this closes.

// 1.x
request.headers['Authorization'] = 'Bearer $accessToken';
request.headers.addAll(proof.headers());

// 2.0
request.headers.addAll(proof.headers());

Three behaviours changed, each of them a fix:

  • htu no longer carries userinfo, and an empty path is now emitted as /. Proofs for https://api.example.com and for URLs with credentials in them change value — in both cases to the one the server was already expecting.
  • DPoPKeyPair.fromPrivateKeyPem and fromPem throw [FormatException] on unreadable input, where 1.x surfaced whatever the underlying library threw. fromPem now also rejects two halves that do not belong together.
  • keyPair.jwk is an unmodifiable map, since it is shared across every proof the key signs rather than rebuilt per call.

basic_utils is no longer a dependency. privateKey and publicKey are the same pointycastle classes they always were, so if you touched them directly, import package:pointycastle/ecc/api.dart instead of package:basic_utils/basic_utils.dart.

License

AGPL-3.0-only — see LICENSE.

About

DPoP proof JWTs for Dart (RFC 9449) — ES256 key handling, PEM storage, JWK thumbprints, access-token binding and server-supplied nonces.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages