For over two decades, web authentication relied on shared secrets—passwords combined with phishable second factors such as SMS one-time codes or RFC 6238 TOTP digits—paired with bearer session tokens (Authorization: Bearer) that granted full account access to any adversary who exfiltrated them via Cross-Site Scripting (XSS), reverse-proxy adversary-in-the-middle (AiTM) phishing kits, browser history leaks, or compromised downstream microservices. When a shared secret traverses the DOM and a bearer token acts as a self-contained capability without cryptographic proof of sender possession, a single point of compromise collapses the entire authentication boundary.
In 2026, production identity and access management (IAM) engineering has completed a structural transition from shared secrets and bearer credentials to origin-bound asymmetric cryptography and application-layer proof-of-possession. That architecture is anchored by four interlocking standards: the W3C Web Authentication (WebAuthn) Level 3 Recommendation (w3.org/TR/webauthn-3/, published 25 August 2026), IETF RFC 9700 / BCP 240 (Best Current Practice for OAuth 2.0 Security, published January 2025), IETF RFC 7636 (Proof Key for Code Exchange - PKCE), and IETF RFC 9449 (OAuth 2.0 Demonstrating Proof of Possession - DPoP), reinforced by IETF RFC 9126 (Pushed Authorization Requests - PAR), IETF RFC 9207 (Authorization Server Issuer Identification), and IETF RFC 9068 (JWT Profile for OAuth 2.0 Access Tokens).

Public Key Cryptography Authentication Ceremony Diagram
This deep-dive engineering guide examines the exact binary byte layouts, bitfield masks, CBOR Object Signing and Encryption (COSE_Key) canonical encodings, ABNF grammars, cryptographic hash transformations, and normative verification state machines required to build phishing-resistant passkey and sender-constrained OAuth systems in 2026. Every byte offset, bitmask, algorithm identifier, HTTP status code, and validation rule below is sourced directly from the official W3C WebAuthn Level 3 and Level 2 Recommendations and the IETF RFC 7636, RFC 8725, RFC 9068, RFC 9126, RFC 9207, RFC 9449, and RFC 9700 specifications.
1. W3C WebAuthn Level 3 Architecture: The 37-Byte authData Binary Layout, Bitfield Flags (UP, UV, BE, BS), and CTAP2 Canonical COSE_Key Encoding
When a Relying Party invokes navigator.credentials.create({ publicKey }) during registration or navigator.credentials.get({ publicKey }) during authentication, the browser (WebAuthn Client) and the hardware or platform authenticator execute the WebAuthn / FIDO2 CTAP2 request-response protocol. Unlike passwords or TOTP codes, the authenticator binds every cryptographic signature both to the caller's TLS web origin (via clientDataJSON) and to the Relying Party Identifier (RP ID) (via the 32-byte rpIdHash inside the binary authenticator data structure). Because the user agent mediates the origin check and the authenticator verifies the RP ID scope, an adversary operating a lookalike phishing domain (https://login-example.evil.com) can never obtain a signature valid for example.com.

Passkey Selection Window and Discoverable Credential Prompt in a Modern Authenticator
The Binary Layout of Authenticator Data (authData)
As defined in W3C WebAuthn Level 3 Section 6.1 (sctn-authenticator-data), the authData structure is a compact, extensible binary byte array of at least 37 bytes signed by the authenticator. During an authentication assertion (authenticatorGetAssertion), the authenticator signs the concatenation of the raw authData bytes and the 32-byte SHA-256 hash of clientDataJSON:
$$\text{SignatureInput} = \text{authData} \;\parallel\; \text{SHA-256}(\text{clientDataJSON})$$
+-----------------------------------------------------------------------+
| rpIdHash (32 bytes / 256 bits) |
| SHA-256 hash of the Relying Party ID (RP ID) the credential is scoped |
+------------------+----------------------------------------------------+
| flags (1 byte) | signCount (4 bytes / 32-bit unsigned big-endian) |
| Bit 0: UP (0x01) | Monotonically increasing signature counter |
| Bit 1: RFU1 | (or 0x00000000 if unmanaged by authenticator) |
| Bit 2: UV (0x04) | |
| Bit 3: BE (0x08) | |
| Bit 4: BS (0x10) | |
| Bit 5: RFU2 | |
| Bit 6: AT (0x40) | |
| Bit 7: ED (0x80) | |
+------------------+----------------------------------------------------+
| attestedCredentialData (variable length, present iff Bit 6 AT == 1) |
| - aaguid (16 bytes) |
| - credentialIdLength (2 bytes, uint16 big-endian L, MUST be <= 1023) |
| - credentialId (L bytes) |
| - credentialPublicKey (variable, CTAP2 canonical CBOR COSE_Key map) |
+-----------------------------------------------------------------------+
| extensions (variable length, present iff Bit 7 ED == 1) |
| - CTAP2 canonical CBOR map (RFC 8949) of authenticator extension outs |
+-----------------------------------------------------------------------+| Byte Offset & Field | Byte Width & Encoding | Bitmask / Constraints | Normative W3C WebAuthn Level 3 Relying Party Verification Rule |
|---|---|---|---|
0..31: rpIdHash |
32 bytes (256-bit binary digest) | Exact 32-byte match | Relying Party MUST compute SHA-256(ASCII(rpId)) locally and verify constant-time byte equality with authData[0..31]. Note that rpId is a registrable domain string (e.g., example.com) without scheme or port. |
32: flags (Bit 0 UP & Bit 2 UV) |
1 byte (8-bit bitfield, LSB = Bit 0) | UP = 0x01, UV = 0x04 |
Bit 0 (UP, User Present) MUST be 1 for standard ceremonies. If Relying Party policy requires User Verification (userVerification: "required"), Bit 2 (UV, (flags & 0x04) != 0) MUST be 1, proving local biometric or PIN verification on the authenticator. |
32: flags (Bit 3 BE & Bit 4 BS) |
1 byte (Bits 3 and 4 of authData[32]) |
BE = 0x08, BS = 0x10 |
Bit 3 (BE, Backup Eligibility) equals 1 for multi-device synced passkeys and 0 for single-device credentials. Bit 4 (BS, Backup State) equals 1 when actively backed up. If BE == 0, BS MUST be 0; Relying Parties MUST reject any response where BE == 0 and BS == 1, or where BE mutates after registration. |
32: flags (Bit 6 AT & Bit 7 ED) |
1 byte (Bits 6 and 7 of authData[32]) |
AT = 0x40, ED = 0x80 |
Bit 6 (AT) MUST be 1 during authenticatorMakeCredential (registration) and 0 during authenticatorGetAssertion (authentication). Bit 7 (ED) indicates presence of a trailing CTAP2 canonical CBOR extension output map. |
33..36: signCount |
4 bytes (32-bit unsigned big-endian integer) | 0 to $2^{32}-1$ |
If either stored signCount > 0 or received signCount > 0, received signCount MUST be strictly greater than stored signCount to detect cloned hardware tokens. Synced multi-device passkeys frequently return constant 0 to prevent cross-device sync race conditions. |
37..54+L: attestedCredentialData |
16B aaguid + 2B L + L B id + COSE_Key |
uint16 L <= 1023 bytes |
credentialIdLength ($L$) at bytes 53..54 is a 16-bit unsigned big-endian integer whose value MUST be $\le 1023$. Followed by $L$ bytes of credentialId and the CTAP2 canonical CBOR COSE_Key map. |
CTAP2 Canonical CBOR COSE_Key Encoding and Registered COSE Algorithm Identifiers
Under W3C WebAuthn Level 3 Section 2.4 (All Conformance Classes) and Section 6.5.1 (sctn-attested-credential-data), all CBOR structures—including credentialPublicKey, attestationObject, and authenticator extensions—MUST use the CTAP2 canonical CBOR encoding form of RFC 8949, and decoders SHOULD reject non-canonical CBOR or maps containing duplicate keys. Specifically, a COSE_Key-encoded credentialPublicKey (RFC 9052 Section 7 / RFC 9053) MUST include the "alg" parameter (label 3) containing a registered COSEAlgorithmIdentifier and MUST NOT contain any optional COSE key parameters (such as kid or key_ops).
In registration ceremonies (PublicKeyCredentialCreationOptions.pubKeyCredParams), Relying Parties specify an ordered array of acceptable COSE algorithm identifiers (alg values from the IANA COSE Algorithms registry):
EdDSA(alg: -8, RFC 8152 / RFC 9053): Edwards-curve Digital Signature Algorithm overEd25519(kty: 1Octet Key PairOKP,crv: 6Ed25519,-2: 32-byte public key byte string). Offers deterministic signing, compact 64-byte signatures, and resistance to side-channel timing and nonce-reuse failures.ES256(alg: -7, RFC 9053 Section 2.1): ECDSA with SHA-256 over the NIST P-256 (secp256r1) curve (kty: 2EC2,crv: 1P-256,-2: 32-byte $x$-coordinate byte string,-3: 32-byte $y$-coordinate byte string). As shown in WebAuthn Level 3 Section 6.5.1.1, a 5-elementES256COSE_Keymap serializes in CTAP2 canonical CBOR hex (where map keys are sorted in canonical CBOR byte order: positive integers01,03, then negative integers20($-1$),21($-2$),22($-3$)) to exactly 77 bytes: ``text A5 # CBOR map of 5 pairs 01 02 # 1 (kty): 2 (EC2) 03 26 # 3 (alg): -7 (ES256, encoded as 0x20 | 6) 20 01 # -1 (crv): 1 (P-256) 21 58 20 <32-byte x-coordinate> # -2 (x): 32-byte bstr (0x58 0x20) 22 58 20 <32-byte y-coordinate> # -3 (y): 32-byte bstr (0x58 0x20)``PS256(alg: -37, RFC 8230 Section 2) andRS256(alg: -257, registered by WebAuthn): RSASSA-PSS with SHA-256 (-37) and RSASSA-PKCS1-v1_5 with SHA-256 (-257) using a 2048-bit RSA key (kty: 3RSA,-1: 256-byte modulus $n$,-2: 3-byte public exponent $e = \text{0x010001}$). Included inpubKeyCredParamsalongside-8and-7to ensure backwards compatibility with Windows Hello TPM 2.0 platform authenticators.
Critical Backup Eligibility (BE) & Backup State (BS) Invariant in WebAuthn Level 3 Section 6.1.3
In WebAuthn Level 3, a passkey's Backup Eligibility (BE, Bit 3 = 0x08) is an immutable property of the public key credential source determined at creation time, whereas Backup State (BS, Bit 4 = 0x10) is a dynamic runtime flag reflecting whether the credential is currently synchronized to cloud keychain storage (such as iCloud Keychain, Google Password Manager, or a third-party passkey vault). Relying Parties enforcing workforce single-device hardware policies must persist the initial BE bit during registration and verify on every subsequent assertion that ((flags & 0x08) != 0) == storedCredential.backupEligible and that !(((flags & 0x08) == 0) && ((flags & 0x10) != 0)).
2. What Changed in W3C WebAuthn Level 3 (August 2026 Recommendation): Related Origins (/.well-known/webauthn), Credential State Signals (signal*), and the prf Extension
On 25 August 2026, the W3C published Web Authentication: An API for accessing Public Key Credentials Level 3 (https://www.w3.org/TR/2026/REC-webauthn-3-20260825/) as a formal W3C Recommendation, superseding the April 8, 2021 Level 2 Recommendation. WebAuthn Level 3 resolves three of the biggest operational bottlenecks that plagued multi-domain enterprise deployments and passkey lifecycle management in Level 2:
1. Cross-Domain Passkey Sharing via Related Origins Requests (Section 5.11)
In WebAuthn Level 1 and Level 2, a credential's RP ID was strictly constrained to equal the caller origin's effective domain or a registrable domain suffix of that effective domain (e.g., https://login.example.com:1337 could specify rpId: "login.example.com" or rpId: "example.com", but never example.co.uk or example.de). Global platforms operating country-specific top-level domains (example.com, example.co.uk, example.de, example.sg) or multi-brand storefronts could not share a single passkey across their properties.
W3C WebAuthn Level 3 Section 5.11 (sctn-related-origins) introduces Related Origins Requests, allowing a Relying Party to choose a single canonical RP ID (for example, example.com) across a bounded set of related web origins by hosting an HTTPS JSON document at the RFC 8615 well-known URI https://<rpId>/.well-known/webauthn:
{
"origins": [
"https://example.co.uk",
"https://example.de",
"https://example.sg",
"https://example.net",
"https://exampledelivery.com",
"https://exampledelivery.co.uk",
"https://myexamplerewards.com",
"https://examplecars.com"
]
}When a script on https://example.de calls navigator.credentials.create() or navigator.credentials.get() with rpId: "example.com", the WebAuthn Client executes the Related Origins Validation Procedure (Section 5.11.1):
- Anonymous HTTPS Fetch: The browser fetches
https://example.com/.well-known/webauthnwithout credentials (no cookies or HTTP auth headers), without a referrer, and strictly using thehttps:scheme (all redirects must also usehttps:). - Strict Content-Type and Status Check: If the HTTP status (after redirects) is not
200, theContent-Typeis notapplication/json, or the body lacks anoriginsarray of strings, the browser immediately aborts the ceremony with a"SecurityError"DOMException. - The Registrable Origin Label Cap (
maxLabels >= 5): To prevent abuse by federated aggregators attempting to share a single tracking credential across hundreds of unrelated domains, the browser extracts the registrable origin label (the label immediately preceding the public suffix, such as"example","exampledelivery","myexamplerewards","examplecars") of each valid entry inoriginsinto a setlabelsSeen. Per Section 5.11, WebAuthn Clients supporting Related Origins MUST support at least 5 registrable origin labels (maxLabels >= 5). Notice thathttps://example.co.uk,https://example.de,https://example.sg, andhttps://example.netall share the single registrable origin label"example"—meaning a company can list dozens of country-code TLDs under a single label slot! OncelabelsSeen.size == maxLabels, any subsequent entry with a new label is ignored during origin matching.
2. Opportunistic Passkey Lifecycle Synchronization via the PublicKeyCredential Signal API (Section 5.1.10)
A chronic user-experience failure in early passkey deployments occurred when a user deleted a passkey in a website's account settings dashboard (or changed their username), leaving an orphaned "ghost passkey" inside the user's OS keychain or password manager. On subsequent logins, the browser autofill UI continued prompting the user to sign in with the revoked passkey, only for the server to reject the assertion.
W3C WebAuthn Level 3 Section 5.1.10 (sctn-signal-methods) standardizes three static methods on PublicKeyCredential so Relying Parties can push credential state updates directly to authenticators:
PublicKeyCredential.signalUnknownCredential({ rpId, credentialId }): Invoked when an authentication assertion presents acredentialId(Base64url string) that no longer exists in the Relying Party database, instructing the platform authenticator to hide or delete the stale credential.PublicKeyCredential.signalAllAcceptedCredentials({ rpId, userId, allAcceptedCredentialIds }): Invoked after login or account settings changes with the user's Base64urluserIdand the complete sequence of valid Base64urlcredentialIdvalues currently registered on the server, allowing the authenticator to garbage-collect any local credentials for thatuserIdmissing from the list.PublicKeyCredential.signalCurrentUserDetails({ rpId, userId, name, displayName }): Synchronizes updated account username (name) and human-readabledisplayNamefields with the authenticator's credential picker UI.
Crucially, Section 5.1.10 enforces a zero-timing-leak privacy invariant: signal methods return a Promise<undefined> that resolves as soon as the input dictionary passes syntax and asynchronous rpId validation, intentionally avoiding waiting for the authenticator to complete the update and never reporting whether a matching credential existed on the device.
3. Native JSON Serialization Helpers, getClientCapabilities(), and the prf Extension
WebAuthn Level 3 also eliminates custom Base64url-to-ArrayBuffer boilerplate and expands client capability introspection:
PublicKeyCredential.parseCreationOptionsFromJSON(optionsJSON)&PublicKeyCredential.parseRequestOptionsFromJSON(optionsJSON)(Sections 5.1.8 & 5.1.9): Convert standard JSON server payloads (where binary fields likechallenge,user.id, andallowCredentials[].idare Base64url-encoded strings) directly into WebAuthn IDL dictionaries containingUint8Arraybuffers, paired withcredential.toJSON()on the returnedPublicKeyCredentialinstance.PublicKeyCredential.getClientCapabilities()(Section 5.1.7): Returns aPromise<Record<string, boolean>>advertising client support for features such asconditionalCreate,conditionalGet(autofill passkeys),hybridTransport(cross-device caBLE / CTAP2 hybrid QR transport),passkeyPlatformAuthenticator,userVerifyingPlatformAuthenticator,relatedOrigins,signalAllAcceptedCredentials,signalCurrentUserDetails, andsignalUnknownCredential.- Pseudo-Random Function (
prf) Extension (Section 10.1.4): Exposes the CTAP2hmac-secretcapability to web applications, allowing a Relying Party to pass one or two 32-byte salt inputs (evalorevalByCredential) and receive deterministic 32-byte symmetric key material derived inside the authenticator (HMAC-SHA-256(credRandom, SHA-256(UTF8("WebAuthn PRF") || 0x00 || salt))) for client-side end-to-end encryption vaults.
3. IETF RFC 9700 (BCP 240) & OAuth 2.1 Security Architecture: The A1–A4 Attacker Model, Implicit/ROPC Removal, and Mix-Up Defense (iss, RFC 9207)
Once a user authenticates at an identity provider using a WebAuthn passkey, the authorization server must issue delegated authorization grants and access tokens to web, mobile, and backend clients. In January 2025, the IETF published RFC 9700 / BCP 240 (Best Current Practice for OAuth 2.0 Security, rfc-editor.org/rfc/rfc9700.txt), formally updating RFC 6749, RFC 6750, and RFC 6819 and establishing the normative security baseline consolidated into OAuth 2.1.
OAuth 2.0 Protocol Delegation Topology Diagram
The Formalized RFC 9700 Section 3 Attacker Model (A1–A4)
Rather than relying on informal threat assumptions, RFC 9700 Section 3 defines four cumulative attacker capability tiers against which every production OAuth 2.0 / 2.1 deployment must be hardened:
| Attacker Class (RFC 9700 §3) | Adversary Capabilities & Observation Vectors | Primary Exploits Enabled | Mandatory Normative Countermeasures (RFC 9700 / RFC 7636 / RFC 9207 / RFC 9449) |
|---|---|---|---|
A1: Web Attacker |
Operates malicious websites, browsers, registered OAuth clients, and rogue Authorization Servers (A-AS) or Resource Servers. Can lure the victim's browser to arbitrary URLs. |
CSRF login fixation, open redirection, Multi-AS Mix-Up attacks, and token phishing at counterfeit resource servers. | Exact redirect_uri string matching (RFC 3986 §6.2.1), zero open redirectors, RFC 9207 iss response validation, RFC 9068 aud restriction, and RFC 9449 DPoP sender-constraining. |
A2: Network Attacker |
Full control over network links (rogue Wi-Fi ARP spoofing, compromised ISP, or IXP). Can intercept, spoof, modify, or block any unencrypted packet. | Interception of non-TLS redirects, Mix-Up with initial HTTP request manipulation, and TLS-termination header spoofing. | End-to-end TLS per BCP 195, strict ban on http:// redirect URIs (except native app loopback per RFC 8252 §7.3), and sanitized reverse-proxy headers (RFC 9700 §4.13). |
A3: Authorization Response Reader |
Can read (but not modify) the authorization response URL via HTTP Referer headers, shared browser history, or malicious native app custom URI scheme hijacking. |
Authorization Code Interception (RFC 7636 §1), Authorization Code Injection into attacker's session (RFC 9700 §4.5), and implicit token theft. | Mandatory PKCE (S256) for public and confidential clients, single-use authorization codes with full token-family revocation on replay, Referrer-Policy: no-referrer, and removal of Implicit Grant. |
A4: Authorization Request Reader |
Can observe the initial authorization request parameters inside the user agent, OS inter-process communication logs, or proxy access logs. | Breaking code_challenge_method=plain PKCE by reading code_challenge directly from the /authorize URL. |
Strict enforcement of one-way cryptographic code_challenge_method=S256 (RFC 7636 §4.2 / RFC 9700 §2.1.1) and Pushed Authorization Requests (PAR, RFC 9126). |
Normative Prohibitions and Hardening Rules in RFC 9700
- Elimination of the Implicit Grant (
response_type=token, Section 2.1.2): Returning access tokens directly in the authorization response URL fragment (https://client.example/cb#access_token=...) exposes live credentials to browser history (Section 4.3.2),Refererheaders due to browser bugs or third-party scripts (Section 4.2), fragment re-attachment across 3xx redirects (Section 4.1.2), and access token injection (Section 4.6). Furthermore, tokens issued at the authorization endpoint cannot be sender-constrained via DPoP or mTLS. RFC 9700 Section 2.1.2 mandates that clients SHOULD NOT use the implicit grant and instead useresponse_type=codewith PKCE. - Absolute Prohibition of Resource Owner Password Credentials (ROPC, Section 2.4): The
grant_type=passwordflow MUST NOT be used. It exposes raw user credentials to client applications, trains users to enter credentials outside the authorization server's origin, and is fundamentally incompatible with origin-scoped cryptographic authenticators such as WebAuthn passkeys. - Exact
redirect_uriString Matching (Section 2.1 & Section 4.1.3): Wildcard pattern matching and subdomain regexes inredirect_urivalidation regularly lead to path-traversal and open-redirector token theft. Authorization servers MUST compare client redirection URIs against pre-registered URIs using exact simple string comparison (RFC 3986 Section 6.2.1), with the sole exception of variable port numbers on127.0.0.1/[::1]loopback interfaces for native applications (RFC 8252 Section 7.3). Additionally, servers can append an arbitrary empty fragment (#_) toLocationredirect headers (Section 4.1.3) to stop browsers from re-attaching a victim's URL fragment across redirects. - HTTP 307 Redirect Hazard Prevention (Section 4.12): When an authorization server redirects an HTTP
POSTrequest containing user credentials, it MUST NOT useHTTP 307 Temporary RedirectorHTTP 308 Permanent Redirect(which instruct the browser to replay thePOSTbody, including the user's credentials, to the target redirect URI) and must instead useHTTP 303 See Other(orHTTP 302 Found). - Multi-AS Mix-Up Attack Defense via
iss(RFC 9207 & RFC 9700 Section 4.4): When an OAuth client supports multiple authorization servers (for instance, enterprise multi-tenant SSO or open banking), an attacker operating a rogue authorization server (A-AS) can intercept the user's login initiation and redirect the browser to an honest authorization server (H-AS), replacing theclient_id. WhenH-ASredirects back to the client's shared callback URI with an authorizationcode, the client mistakenly believes the code came fromA-ASand sends thecodestraight toA-AS's token endpoint! IETF RFC 9207 defeats this by requiring the authorization server to advertise"authorization_response_iss_parameter_supported": truein its RFC 8414 discovery metadata and include its exact issuer URL (&iss=https%3A%2F%2Fhonest.as.example) in every authorization and error redirect response. The client validatesissvia RFC 3986 Section 6.2.1 simple string comparison against the issuer stored in the session when the flow began.
4. Proof Key for Code Exchange (PKCE, IETF RFC 7636): code_verifier Entropy (43*128unreserved), S256 Transformation, and Downgrade Mitigation
Originally designed in IETF RFC 7636 (rfc-editor.org/rfc/rfc7636.txt) to protect mobile native applications from custom URI scheme hijacking (Attacker A3), PKCE (pronounced "pixy") is now mandated by RFC 9700 Section 2.1.1 across all OAuth clients—both public clients (SPAs, mobile apps, CLI tools) and confidential backend clients—to prevent Authorization Code Interception and Authorization Code Injection (where an attacker injects a stolen authorization code into their own browser session with a confidential client to bind their session to the victim's account).
Normative ABNF Grammar, Entropy Mathematics, and the RFC 7636 Appendix B Test Vector
Per RFC 7636 Section 4.1 and Section 7.1, before initiating an authorization request, the client generates a fresh, transaction-specific cryptographic secret called the code_verifier:
code-verifier = 43*128unreserved
code-challenge = 43*128unreserved
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
ALPHA = %x41-5A / %x61-7A
DIGIT = %x30-39- Minimum 256-Bit Entropy (32 Octets $\rightarrow$ 43 Base64url Characters): RFC 7636 Section 7.1 specifies that the client SHOULD generate
code_verifierwith a minimum of 256 bits of entropy by drawing a 32-octet sequence from a cryptographically secure random number generator (CSPRNG) and applying Base64url encoding without=padding (RFC 4648 Section 5 / RFC 7636 Appendix A: replacing+with-,/with_, and stripping trailing=). Because $\lceil 32 \times 8 / 6 \rceil = 43$, a 32-octet random sequence always produces an exact 43-character URL-safe ASCII string—matching the lower bound of43*128unreserved. (Why no salting? As explained in RFC 7636 Section 7.3, salting is omitted because 256 bits of entropy already renders offline dictionary and GPU brute-force attacks mathematically infeasible). - Mandatory-To-Implement (MTI)
S256Transformation (Section 4.2): The client computescode_challengefrom the ASCII octets ofcode_verifier: $$\text{code\_challenge} = \text{BASE64URL-ENCODE}(\text{SHA256}(\text{ASCII}(\text{code\_verifier})))$$ Per Section 4.2,"S256"is Mandatory To Implement on the server, and any client capable of SHA-256 MUST use"S256"and MUST NOT downgrade to"plain"(Section 7.2). Note that under RFC 7636 Section 4.3, if a client omitscode_challenge_methodin/authorize, the protocol default is"plain"—meaning production authorization servers enforcing RFC 9700 must explicitly reject requests wherecode_challenge_method != "S256"witherror=invalid_request. - Official RFC 7636 Appendix B Verification Vector:
- Input 32-octet sequence:
[116, 24, 223, 180, 151, 153, 224, 37, 79, 250, 96, 125, 216, 173, 187, 186, 22, 212, 37, 77, 105, 214, 191, 240, 91, 88, 5, 88, 83, 132, 141, 121] - Base64url-encoded
code_verifier(43 chars):dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk - SHA-256 digest (32 octets):
[19, 211, 30, 150, 26, 26, 216, 236, 47, 22, 177, 12, 76, 152, 46, 8, 118, 168, 120, 173, 109, 241, 68, 86, 110, 225, 137, 74, 203, 112, 249, 195] - Base64url-encoded
code_challenge(43 chars):E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
Defeating the PKCE Downgrade Attack (RFC 9700 Section 2.1.1 & Section 4.8.2)
A subtle vulnerability occurs in authorization servers that enforce PKCE only when code_challenge is present in the authorization request. In a PKCE Downgrade Attack, an attacker starts an authorization flow without a code_challenge, steals a victim's authorization code, or tricks the client into redeeming a non-PKCE code while sending its generated code_verifier to the token endpoint. If the token endpoint simply ignores code_verifier whenever the stored authorization code has no associated code_challenge, code injection succeeds! Per RFC 9700 Section 2.1.1, authorization servers MUST ensure that any token request containing a code_verifier parameter is rejected with error="invalid_grant" if no code_challenge was present in the initial authorization request.
5. OAuth 2.0 Demonstrating Proof of Possession (DPoP, IETF RFC 9449): dpop+jwt Structure, ath Access Token Hash, cnf.jkt Thumbprints, and DPoP-Nonce State Machines
Even when WebAuthn Level 3 and PKCE S256 protect the initial authentication and code exchange, a traditional Bearer access token (RFC 6750) remains a high-value liability: any XSS payload, compromised CDN edge worker, leaked log file, or rogue downstream microservice that captures the token string can replay it from any machine on the internet until it expires. While Mutual TLS (mTLS, RFC 8705) binds tokens to X.509 client certificates at the transport layer, browser Single-Page Applications (SPAs) and mobile WebViews cannot ergonomically manage mTLS client certificates or survive TLS-terminating CDN proxies.
IETF RFC 9449 (OAuth 2.0 Demonstrating Proof of Possession - DPoP, published September 2023, rfc-editor.org/rfc/rfc9449.txt) solves this at the application layer. The client generates an asymmetric key pair (for example, a non-extractable ES256 P-256 CryptoKeyPair stored in browser IndexedDB via the W3C WebCrypto API) and attaches a short-lived, request-specific DPoP Proof JWT in the DPoP HTTP request header whenever talking to the Token Endpoint or a Protected Resource Server.
+--------+ +----------------------+
| |---(1) GET /authorize -------------------->| |
| | + code_challenge (S256) | |
| | + dpop_jkt (SHA-256 JWK Thumbprint) | Authorization Server |
| |<--(2) 302 code + iss (RFC 9207) ----------| |
| | | |
| |---(3) POST /token ----------------------->| |
| Client | + code_verifier | Validates PKCE + |
| (Key | + DPoP: <dpop+jwt signed by sk_C> | verifies dpop_jkt == |
| Pair |<--(4) 200 OK token_type="DPoP" -----------| JWK thumbprint(pk_C) |
| pk_C, | access_token (cnf.jkt = JWK hash) +----------------------+
| sk_C) | DPoP-Nonce: <next_server_nonce>
| | +----------------------+
| |---(5) GET /api/v1/orders ---------------->| |
| | Authorization: DPoP <access_token> | Resource Server |
| | DPoP: <dpop+jwt with ath + nonce> | Verifies sig, htm, |
| |<--(6) 200 OK Protected Resource ----------| htu, ath, & cnf.jkt |
+--------+ +----------------------+Anatomy of a DPoP Proof JWT (RFC 9449 Section 4.2) and the cnf.jkt Binding (Section 6.1)
Every HTTP request carrying a DPoP proof includes a DPoP header (token68 syntax) whose decoded JOSE Header and JWT Payload MUST conform to RFC 9449 Section 4.2:
// 1. DPoP Proof JOSE Header (RFC 9449 Section 4.2)
{
"typ": "dpop+jwt",
"alg": "ES256",
"jwk": {
"kty": "EC",
"crv": "P-256",
"x": "l8tFrhx-34tV3hRICRDY9zCkDlpBhF42UQUfWVAWBFs",
"y": "9VE4jf_Ok_o64zbTTlcuNJajHmt6v9TDVrU0CdvGRDA"
}
}
// 2. DPoP Proof JWT Payload for Protected Resource Access (RFC 9449 Section 7.1)
{
"jti": "e1j3V_bKic8-LAEB",
"htm": "GET",
"htu": "https://resource.example.org/protectedresource",
"iat": 1562262618,
"ath": "fUHyO2r2Z3DZ53EsNrWBb0xWXoaNy59IiKCAqksmQEo",
"nonce": "eyJ7S_zG.eyJH0-Z.HX4w-7v"
}When the Authorization Server issues a DPoP-bound JWT access token (token_type: "DPoP"), it computes the RFC 7638 JWK SHA-256 Thumbprint of the client's public key—lexicographically sorting only the required JWK members for that key type with zero whitespace ({"crv":"P-256","kty":"EC","x":"...","y":"..."}), hashing the UTF-8 string with SHA-256, and Base64url-encoding the digest—and embeds it inside the access token's cnf (Confirmation, RFC 7800) claim under the jkt member (Section 6.1):
{
"iss": "https://server.example.com",
"sub": "someone@example.com",
"aud": "https://resource.example.org",
"client_id": "s6BhdRkqt3",
"nbf": 1562262611,
"exp": 1562266216,
"iat": 1562262611,
"jti": "dbe39bf3a3ba4238a513f51d6e1691c4",
"cnf": {
"jkt": "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"
}
}The 12-Step Normative Server Verification Checklist for DPoP Proofs (RFC 9449 Section 4.3)
Under RFC 9449 Section 4.3 (Checking DPoP Proofs), a receiving Authorization Server or Resource Server MUST verify all twelve invariants before accepting a request:
| Check # | DPoP Parameter / Header | Normative RFC 9449 Validation Requirement | Rejection Error & HTTP Status Code |
|---|---|---|---|
| 1 & 2 | DPoP HTTP Header |
Exactly one DPoP HTTP request header field is present, and its value is a single, well-formed compact JWS/JWT. |
AS: 400 invalid_dpop_proofRS: 401 invalid_dpop_proof |
| 3 & 4 | JOSE typ & Required Claims |
JOSE Header typ MUST equal "dpop+jwt" (explicit typing per RFC 8725 §3.11). Payload MUST contain jti (≥ 96 bits entropy / UUIDv4), htm, htu, and iat. |
AS: 400 invalid_dpop_proofRS: 401 invalid_dpop_proof |
| 5, 6 & 7 | JOSE alg & jwk |
alg MUST be a registered asymmetric JWS algorithm (e.g., ES256, PS256, EdDSA)—never none or symmetric HMAC. jwk MUST NOT contain private key fields (d, p, q), and JWS signature MUST verify against jwk. |
AS: 400 invalid_dpop_proofRS: 401 invalid_dpop_proof |
| 8 & 9 | Payload htm & htu |
htm MUST match the HTTP method (e.g., POST, GET). htu MUST match the HTTP target URI ignoring query and fragment parts (after RFC 3986 §6.2.2/6.2.3 syntax and scheme normalization). |
AS: 400 invalid_dpop_proofRS: 401 invalid_dpop_proof |
| 10 & 11 | Payload nonce, iat & jti Replay |
If server issued a DPoP-Nonce challenge, nonce MUST match. Creation timestamp iat MUST fall within a narrow acceptance window (e.g., ±60s), and jti MUST NOT have been seen before in that window. |
Missing/stale nonce: AS: 400 use_dpop_nonceRS: 401 use_dpop_nonce |
| 12 | Payload ath & Token cnf.jkt |
On Resource Servers: ath MUST equal BASE64URL(SHA256(ASCII(access_token))), and the RFC 7638 SHA-256 thumbprint of the proof's jwk MUST equal the access token's cnf.jkt claim. |
Key mismatch: 401 invalid_tokenBad ath: 401 invalid_dpop_proof |
Why ath, DPoP-Nonce, dpop_jkt, and Bearer Anti-Downgrade Rules Are Critical
- Preventing Token Swapping with
ath(Section 7): Suppose a client uses the same DPoP key pair for two different access tokens (AT1andAT2) or rotates an access token via a refresh grant. Without theathclaim (BASE64URL-ENCODE(SHA256(ASCII(access_token)))), an attacker who captures a DPoP proof sent withAT1could attach that proof toAT2on the same endpoint. Signingathinside the DPoP proof cryptographically binds the proof to that exact access token string. - Defeating XSS Proof Pre-Generation with
DPoP-Nonce(Sections 8, 9 & 11.2): Even when a browser client stores its DPoP private key as a non-extractable WebCryptoCryptoKey, a transient XSS payload executing inside the page can callcrypto.subtle.sign()to pre-generate thousands of DPoP proofs with futureiattimestamps and exfiltrate them alongside the refresh or access token. By requiring a server-generated, unpredictableDPoP-Nonceresponse header (returned onHTTP 400/HTTP 401witherror="use_dpop_nonce"or rotated proactively onHTTP 200 OKwithCache-Control: no-store), the server guarantees that no valid DPoP proof can be pre-computed before the server issues the current time window's nonce. Note: For browser CORS clients, servers MUST includeDPoP-NonceandWWW-AuthenticateinAccess-Control-Expose-Headers(Sections 7.1 and 8). - Binding Refresh Tokens for Public Clients vs. Confidential Clients (Section 5): When an Authorization Server issues a refresh token to a public client presenting a DPoP proof, the refresh token MUST be bound to that DPoP public key and verified on every
grant_type=refresh_tokenrequest. By contrast, refresh tokens issued to confidential clients are not bound to the DPoP key because they are already bound to the client's authenticatedclient_idcredentials, allowing confidential clients to rotate keys without invalidating existing refresh tokens. - End-to-End Authorization Code Binding via
dpop_jkt(Section 10): To eliminate any gap between/authorizeand/token, the client sends&dpop_jkt=<JWK_SHA256_Thumbprint>in the initial authorization request alongside&code_challenge=<S256>&code_challenge_method=S256. At the/tokenendpoint, the Authorization Server verifies both PKCE (SHA256(code_verifier) == code_challenge) and that theDPoPheader'sjwkthumbprint equalsdpop_jkt. - Dual-Scheme Bearer Anti-Downgrade Invariant (Section 7.2): If a Resource Server supports both
BearerandDPoPschemes during a migration, it MUST inspect every token presented viaAuthorization: Bearer <token>and reject the request if the token contains acnf.jktDPoP binding (token_type == "DPoP"). Accepting a DPoP-bound token over theBearerscheme strips all sender-constraining protection. And if a client sends bothAuthorization: Bearer ...andAuthorization: DPoP ...in the same request, the Resource Server responds withHTTP 400 Bad Request(error="invalid_request", Figure 19 of RFC 9449).
6. Hardening the Front Channel and Token Formats: Pushed Authorization Requests (PAR, RFC 9126) and JWT Access Tokens (at+jwt, RFC 9068 & RFC 8725)
In conventional OAuth 2.0 flows, authorization request parameters (client_id, redirect_uri, scope, code_challenge, dpop_jkt, and fine-grained authorization_details) are passed as front-channel URL query parameters through the user's browser. That creates three severe engineering problems: (1) an attacker can tamper with scope or parameters before the browser hits /authorize; (2) sensitive request metadata leaks into browser history, proxy logs, and Referer headers; and (3) rich authorization payloads exceed browser or CDN URL length limits.
Pushed Authorization Requests (PAR, IETF RFC 9126)
IETF RFC 9126 (rfc-editor.org/rfc/rfc9126.txt) moves authorization request initiation from the browser front-channel to a direct, authenticated back-channel POST request (Content-Type: application/x-www-form-urlencoded, UTF-8) to the Authorization Server's pushed_authorization_request_endpoint (advertised in RFC 8414 metadata alongside "require_pushed_authorization_requests": true):
POST /as/par HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7...
response_type=code&client_id=s6BhdRkqt3
&redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
&scope=openid%20payments%3Awrite
&state=af0ifjsldkj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
&dpop_jkt=0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJraWQiOiJrMmJkYyIsImFsZyI6IkVTMjU2In0...Per RFC 9126 Sections 2.1, 2.2, 2.3, and 10.1 (of RFC 9449):
- Early Client Authentication and
request_uriProhibition: The Authorization Server authenticates the client (e.g., via asymmetricprivate_key_jwtwhereaudis the AS issuer identifier, token endpoint, or PAR endpoint) and validates all parameters before any user interaction occurs. If the incoming PAR POST body contains arequest_uriparameter, the server MUST reject it (HTTP 400 invalid_request). Note that per RFC 9449 Section 10.1, a client can bind the authorization code to its DPoP key during PAR either by sendingdpop_jktin the PAR form body or by attaching aDPoPproof header directly to thePOST /as/parrequest! HTTP 201 Createdand Ephemeral Single-Use URN (5–600Seconds): On success, the server returnsHTTP 201 Created(Cache-Control: no-cache, no-store) with a cryptographically random, single-userequest_uribound to thatclient_idand a shortexpires_inlifetime (typically 5 to 600 seconds, e.g.,60seconds): ``json { "request_uri": "urn:ietf:params:oauth:request_uri:6esc_11ACC5bwc014ltc14eY22c", "expires_in": 60 }`The client then redirects the browser to/authorize?client_id=s6BhdRkqt3&request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3A6esc_11ACC5bwc014ltc14eY22c`.- Normative PAR Error Status Codes (Section 2.3): In addition to
400 Bad Request(invalid_request,invalid_client,invalid_dpop_proof), a compliant PAR endpoint uses405 Method Not Allowedif the HTTP method is notPOST,413 Payload Too Largeif the payload exceeds server size limits, and429 Too Many Requestswhen rate-limiting a client.
Eliminating Cross-JWT Confusion with RFC 9068 (at+jwt) and RFC 8725 (BCP 225)
When resource servers validate stateless JWT access tokens locally, a dangerous vulnerability class documented in IETF RFC 8725 Section 2.8 and Section 3.11 (JSON Web Token Best Current Practices / BCP 225) and IETF RFC 9068 (JWT Profile for OAuth 2.0 Access Tokens) is Cross-JWT Confusion: if an Authorization Server signs OpenID Connect id_tokens, Session Logout tokens (secevent+jwt, RFC 8417), and API access tokens with the same jwks_uri key set, an attacker can take an id_token (or a client's dpop+jwt proof) and replay it as an API access token against a Resource Server that fails to check explicit JWT typing.
RFC 9068 Sections 2.1, 2.2, and 4 prevent this through strict structural rules:
- Mandatory Explicit Typing (
typ: "at+jwt"): Every JWT access token MUST set its JOSE Headertypparameter to"at+jwt"(or"application/at+jwt"), and Resource Servers MUST reject any access token whosetypheader is not"at+jwt"or"application/at+jwt". - Asymmetric Signing Only (
alg != "none"): Tokens MUST be signed with an asymmetric algorithm (RS256is MTI for RFC 9068 interoperability alongsideES256/EdDSA), and Resource Servers MUST reject"alg": "none"and validate the signature exclusively against keys advertised in the Authorization Server's RFC 8414jwks_uri. - The 7 Required Payload Claims (Section 2.2): Every RFC 9068 JWT access token MUST include
iss(issuer URL),exp(expiration timestamp),aud(target resource indicator per RFC 8707—Resource Servers MUST reject any token whoseauddoes not identify them),sub(resource owner subject ID, or client ID forclient_credentialsgrants—where AS MUST prevent clients from choosing arbitraryclient_idvalues that collide with humansubIDs, per Section 5),client_id,iat, andjti.
7. Production Reference Implementation: Zero-Trust WebAuthn Level 3 (authData) & DPoP (RFC 9449) Verification Engine in Python 3
Below is a self-contained, dependency-free Python 3 reference verifier implementing the exact binary and cryptographic checks required by W3C WebAuthn Level 3 Sections 6.1 & 6.5.1, IETF RFC 7636 Section 4.6 (PKCE S256), and IETF RFC 9449 Section 4.3 & Section 6.1 (DPoP Proof & JWK SHA-256 Thumbprint Confirmation).
#!/usr/bin/env python3
"""Production Reference Verifier for W3C WebAuthn Level 3, RFC 7636 PKCE, and RFC 9449 DPoP.
Implements:
1. W3C WebAuthn Level 3 Section 6.1 & 6.5.1 binary authData parser & bitfield validator
2. IETF RFC 7636 Section 4.6 constant-time PKCE S256 verifier (verified against Appendix B)
3. IETF RFC 9449 Section 4.3 & 6.1 DPoP proof claims, ath hash, and RFC 7638 JWK thumbprint
"""
from __future__ import annotations
import base64
from dataclasses import dataclass
import hashlib
import hmac
import json
import re
import struct
import time
from urllib.parse import urlsplit, urlunsplit
# W3C WebAuthn Level 3 Section 6.1 Bitfield Masks (Bit 0 = LSB)
FLAG_UP: int = 0x01 # Bit 0: User Present
FLAG_RFU1: int = 0x02 # Bit 1: Reserved
FLAG_UV: int = 0x04 # Bit 2: User Verified
FLAG_BE: int = 0x08 # Bit 3: Backup Eligibility (multi-device passkey)
FLAG_BS: int = 0x10 # Bit 4: Backup State (currently backed up)
FLAG_RFU2: int = 0x20 # Bit 5: Reserved
FLAG_AT: int = 0x40 # Bit 6: Attested Credential Data Included
FLAG_ED: int = 0x80 # Bit 7: Extension Data Included
_PKCE_VERIFIER_RE = re.compile(r"^[A-Za-z0-9\-._~]{43,128}$")
_ASYMMETRIC_JWS_ALGS = frozenset({"ES256", "ES384", "ES512", "EdDSA", "PS256", "PS384", "PS512", "RS256"})
def b64url_encode(data: bytes) -> str:
"""RFC 4648 Section 5 Base64url encoding without '=' padding."""
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def b64url_decode(text: str) -> bytes:
"""RFC 4648 Section 5 Base64url decoding with automatic padding restoration."""
pad = "=" * ((4 - len(text) % 4) % 4)
return base64.urlsafe_b64decode((text + pad).encode("ascii"))
@dataclass(frozen=True)
class ParsedAuthenticatorData:
"""Immutable representation of W3C WebAuthn Level 3 Section 6.1 authData."""
rp_id_hash: bytes
flags: int
user_present: bool
user_verified: bool
backup_eligible: bool
backup_state: bool
attested_credential_data_present: bool
extension_data_present: bool
sign_count: int
aaguid: bytes | None = None
credential_id: bytes | None = None
cose_public_key_bytes: bytes | None = None
def parse_and_verify_webauthn_auth_data(
auth_data: bytes,
expected_rp_id: str,
require_user_verification: bool = True,
is_registration: bool = False,
stored_backup_eligible: bool | None = None,
stored_sign_count: int = 0,
) -> ParsedAuthenticatorData:
"""Parse and validate a W3C WebAuthn Level 3 37+ byte authData buffer."""
if len(auth_data) < 37:
raise ValueError(f"WebAuthn authData too short: {len(auth_data)} bytes < 37 minimum")
rp_id_hash = auth_data[:32]
flags, sign_count = struct.unpack(">BI", auth_data[32:37])
expected_hash = hashlib.sha256(expected_rp_id.encode("ascii")).digest()
if not hmac.compare_digest(rp_id_hash, expected_hash):
raise ValueError("WebAuthn rpIdHash mismatch against expected RP ID")
up = (flags & FLAG_UP) != 0
uv = (flags & FLAG_UV) != 0
be = (flags & FLAG_BE) != 0
bs = (flags & FLAG_BS) != 0
at = (flags & FLAG_AT) != 0
ed = (flags & FLAG_ED) != 0
if not up:
raise ValueError("WebAuthn Bit 0 (UP - User Present) MUST be 1")
if require_user_verification and not uv:
raise ValueError("WebAuthn Bit 2 (UV - User Verified) required by RP policy but was 0")
# WebAuthn Level 3 Section 6.1.3 invariant: BS cannot be 1 if BE is 0
if not be and bs:
raise ValueError("Invalid WebAuthn Level 3 backup state: BE == 0 while BS == 1")
if stored_backup_eligible is not None and be != stored_backup_eligible:
raise ValueError("WebAuthn Level 3 violation: immutable BE flag mutated after registration")
if is_registration and not at:
raise ValueError("WebAuthn registration requires Bit 6 (AT) == 1")
if not is_registration and at:
raise ValueError("WebAuthn authentication assertion MUST NOT set Bit 6 (AT)")
if not is_registration and (stored_sign_count > 0 or sign_count > 0):
if sign_count <= stored_sign_count:
raise ValueError(
f"WebAuthn signCount clone anomaly: received {sign_count} <= stored {stored_sign_count}"
)
aaguid: bytes | None = None
credential_id: bytes | None = None
cose_public_key_bytes: bytes | None = None
if at:
# Section 6.5.1 Attested Credential Data: 16B aaguid + 2B uint16 L (<= 1023) + L bytes id + COSE_Key
if len(auth_data) < 37 + 18:
raise ValueError("Truncated WebAuthn attestedCredentialData header")
aaguid = auth_data[37:53]
(cred_id_len,) = struct.unpack(">H", auth_data[53:55])
if cred_id_len > 1023:
raise ValueError(f"WebAuthn credentialIdLength {cred_id_len} exceeds 1023-byte limit")
end_id = 55 + cred_id_len
if len(auth_data) <= end_id:
raise ValueError("Truncated WebAuthn credentialId or missing COSE_Key")
credential_id = auth_data[55:end_id]
cose_public_key_bytes = auth_data[end_id:]
return ParsedAuthenticatorData(
rp_id_hash=rp_id_hash,
flags=flags,
user_present=up,
user_verified=uv,
backup_eligible=be,
backup_state=bs,
attested_credential_data_present=at,
extension_data_present=ed,
sign_count=sign_count,
aaguid=aaguid,
credential_id=credential_id,
cose_public_key_bytes=cose_public_key_bytes,
)
def verify_pkce_s256(
code_verifier: str,
stored_code_challenge: str | None,
stored_method: str | None = "S256",
) -> bool:
"""Verify RFC 7636 PKCE S256 with RFC 9700 Section 4.8.2 anti-downgrade enforcement."""
# RFC 9700 Section 2.1.1 / 4.8.2: Reject token request with code_verifier if no code_challenge was bound
if not stored_code_challenge or stored_method != "S256":
raise ValueError("invalid_grant: PKCE S256 challenge missing or downgrade attempted")
if not _PKCE_VERIFIER_RE.match(code_verifier):
raise ValueError("invalid_grant: code_verifier violates RFC 7636 43*128unreserved ABNF")
computed_challenge = b64url_encode(hashlib.sha256(code_verifier.encode("ascii")).digest())
if not hmac.compare_digest(computed_challenge, stored_code_challenge):
raise ValueError("invalid_grant: PKCE S256 code_verifier mismatch")
return True
def compute_rfc7638_jwk_thumbprint(jwk: dict[str, str]) -> str:
"""Compute the RFC 7638 JWK SHA-256 Thumbprint for RFC 9449 cnf.jkt and dpop_jkt."""
# RFC 9449 Section 4.3 Check 7: Public JWK in DPoP header MUST NOT contain private key material
forbidden_private_fields = {"d", "p", "q", "dp", "dq", "qi", "oth", "k"}
if forbidden_private_fields.intersection(jwk.keys()):
raise ValueError("invalid_dpop_proof: JWK contains forbidden private key parameters")
kty = jwk.get("kty")
if kty == "EC":
canonical = {"crv": jwk["crv"], "kty": "EC", "x": jwk["x"], "y": jwk["y"]}
elif kty == "OKP":
canonical = {"crv": jwk["crv"], "kty": "OKP", "x": jwk["x"]}
elif kty == "RSA":
canonical = {"e": jwk["e"], "kty": "RSA", "n": jwk["n"]}
else:
raise ValueError(f"invalid_dpop_proof: unsupported JWK kty '{kty}'")
canonical_json = json.dumps(canonical, separators=(",", ":"), sort_keys=True).encode("utf-8")
return b64url_encode(hashlib.sha256(canonical_json).digest())
def normalize_htu(uri: str) -> str:
"""RFC 9449 Section 4.3 Check 9: Strip query and fragment and normalize scheme/host."""
parts = urlsplit(uri)
scheme = parts.scheme.lower()
netloc = parts.netloc.lower()
if (scheme == "https" and netloc.endswith(":443")) or (scheme == "http" and netloc.endswith(":80")):
netloc = netloc.rsplit(":", 1)[0]
path = parts.path or "/"
return urlunsplit((scheme, netloc, path, "", ""))
def validate_dpop_proof_claims(
dpop_jwt: str,
http_method: str,
http_target_uri: str,
seen_jtis: set[str],
access_token: str | None = None,
expected_cnf_jkt: str | None = None,
expected_server_nonce: str | None = None,
now_epoch: int | None = None,
max_clock_skew_seconds: int = 60,
) -> str:
"""Execute RFC 9449 Section 4.3 structural, binding, and replay checks on a DPoP proof."""
segments = dpop_jwt.split(".")
if len(segments) != 3:
raise ValueError("invalid_dpop_proof: DPoP header is not a 3-part JWS compact serialization")
header = json.loads(b64url_decode(segments[0]).decode("utf-8"))
payload = json.loads(b64url_decode(segments[1]).decode("utf-8"))
# Check 4 & 5: Explicit typing (dpop+jwt) and asymmetric JWS algorithm
if header.get("typ") != "dpop+jwt":
raise ValueError("invalid_dpop_proof: JOSE header typ MUST be 'dpop+jwt'")
if header.get("alg") not in _ASYMMETRIC_JWS_ALGS:
raise ValueError(f"invalid_dpop_proof: unacceptable JWS alg '{header.get('alg')}'")
jwk = header.get("jwk")
if not isinstance(jwk, dict):
raise ValueError("invalid_dpop_proof: missing jwk in JOSE header")
proof_jkt = compute_rfc7638_jwk_thumbprint(jwk)
# Check 3, 8, 9, 10, 11: Required claims (jti, htm, htu, iat)
for req_claim in ("jti", "htm", "htu", "iat"):
if req_claim not in payload:
raise ValueError(f"invalid_dpop_proof: missing required claim '{req_claim}'")
if payload["htm"] != http_method.upper():
raise ValueError("invalid_dpop_proof: htm claim does not match HTTP request method")
if normalize_htu(payload["htu"]) != normalize_htu(http_target_uri):
raise ValueError("invalid_dpop_proof: htu claim does not match target URI without query/fragment")
if expected_server_nonce is not None:
if payload.get("nonce") != expected_server_nonce:
raise ValueError("use_dpop_nonce: missing or mismatched server-provided DPoP-Nonce")
current_time = int(time.time()) if now_epoch is None else now_epoch
if abs(current_time - int(payload["iat"])) > max_clock_skew_seconds:
raise ValueError("invalid_dpop_proof: iat timestamp outside acceptable clock window")
jti = str(payload["jti"])
if jti in seen_jtis:
raise ValueError("invalid_dpop_proof: DPoP proof replay detected via duplicate jti")
seen_jtis.add(jti)
# Check 12: Protected resource access token hash (ath) and public key thumbprint (cnf.jkt)
if access_token is not None:
expected_ath = b64url_encode(hashlib.sha256(access_token.encode("ascii")).digest())
if not hmac.compare_digest(str(payload.get("ath", "")), expected_ath):
raise ValueError("invalid_dpop_proof: ath claim does not match SHA-256 hash of access token")
if expected_cnf_jkt is not None and not hmac.compare_digest(proof_jkt, expected_cnf_jkt):
raise ValueError("invalid_token: DPoP proof JWK thumbprint does not match token cnf.jkt")
return proof_jkt8. Frequently Asked Questions (FAQ)
1. Why can a WebAuthn Level 3 multi-device passkey have Backup Eligibility (BE = 1) while Backup State (BS = 0), and why is (BE = 0, BS = 1) strictly rejected? In W3C WebAuthn Level 3 Section 6.1 and Section 6.1.3, Bit 3 (BE, mask 0x08) indicates whether the credential source is architecturally capable of being backed up or synced across devices (a multi-device credential), whereas Bit 4 (BS, mask 0x10) indicates whether the credential is currently backed up at the exact moment of the ceremony. If a user creates a passkey on a smartphone where cloud keychain sync is temporarily disabled, the platform authenticator sets BE = 1 and BS = 0; if the user later enables cloud sync, BS transitions to 1 while BE remains 1. Conversely, a single-device hardware credential (BE = 0) can never be backed up, so the bit combination (BE = 0, BS = 1) is a protocol violation that compliant Relying Parties must reject.
2. How does W3C WebAuthn Level 3 Related Origins (/.well-known/webauthn) prevent a malicious conglomerate from tracking users across dozens of unrelated domains? Under WebAuthn Level 3 Section 5.11.1, when a WebAuthn Client fetches https://<rpId>/.well-known/webauthn, it does not simply count raw origin strings—it parses the effective domain of each origin and extracts its registrable origin label (the domain label immediately to the left of the public suffix, such as "example" in example.co.uk, example.de, and example.sg). The browser tracks unique labels in a set labelsSeen capped by maxLabels (where compliant browsers MUST support at least 5 registrable origin labels). This allows an enterprise with 30 country-code TLDs sharing the "example" brand label to consume only 1 label slot, while preventing abuse across more than the browser's small cap of distinct domain brands.
3. Why does IETF RFC 9700 (BCP 240) recommend PKCE (S256) even for confidential backend OAuth clients that already authenticate with a client secret or private_key_jwt? Client authentication at the /token endpoint only proves to the Authorization Server that the client application redeeming the authorization code is legitimate—it does not prove that the authorization code being redeemed belongs to the same end-user browser session that initiated the login! In an Authorization Code Injection attack (RFC 9700 Section 4.5), an attacker steals a victim's authorization code (via a Referer header leak, shared device history, or open redirector) and injects that code into the callback URL of the attacker's own login session on the legitimate confidential client. The confidential client attaches its own valid client_secret or private_key_jwt and redeems the victim's code, logging the attacker into the victim's account. Binding the session to a transaction-specific PKCE code_verifier stops code injection cold because the attacker does not know the victim session's code_verifier.
4. Why does an RFC 9449 DPoP Proof JWT sign only htm (HTTP method) and htu (HTTP URI without query/fragment) rather than the full HTTP headers and request body? As explained in IETF RFC 9449 Section 4.2 and Section 11.7, HTTP requests frequently traverse reverse proxies, API gateways, load balancers, and CDNs that rewrite, reorder, or fold HTTP headers and normalize query parameters. Attempting to canonicalize full HTTP headers and bodies across intermediary hops introduces severe interoperability failures. RFC 9449 intentionally signs the minimal invariant tuple—htm, htu (stripped of query and fragment), iat, jti, ath (the SHA-256 hash of the access token), and optional nonce—to prove live private-key possession for that target endpoint while relying on TLS (BCP 195) for transport message integrity.
5. If a browser Single-Page Application (SPA) suffers a Cross-Site Scripting (XSS) vulnerability, what does DPoP (RFC 9449) protect against—and what remains out of scope? Per RFC 9449 Section 2 and Section 11.4, when an SPA generates its DPoP private key as a non-extractable WebCrypto CryptoKey (extractable: false), an XSS payload cannot exfiltrate the private key to an external command-and-control server. Therefore, stealing the access token or refresh token string from memory or localStorage is useless outside the victim's browser session. Furthermore, enabling server-issued DPoP-Nonce headers (Sections 8 and 9) prevents the XSS script from pre-generating future-dated DPoP proofs for offline use. However, while the XSS payload remains actively executing inside the victim's browser tab, it can invoke the browser's signing API in-context to make unauthorized API calls—which is why Content Security Policy (CSP) and XSS elimination remain mandatory defense-in-depth layers.
9. Official Specifications & Primary Sources
Every byte offset, bitfield flag, CBOR/COSE encoding rule, ABNF grammar, HTTP status code, and cryptographic verification procedure in this guide was verified directly against the following normative W3C and IETF specifications fetched during this session:
- W3C Web Authentication: An API for accessing Public Key Credentials — Level 3 (W3C Recommendation, 25 August 2026): https://www.w3.org/TR/webauthn-3/ and https://www.w3.org/TR/2026/REC-webauthn-3-20260825/
- W3C Web Authentication: An API for accessing Public Key Credentials — Level 2 (W3C Recommendation, 8 April 2021): https://www.w3.org/TR/webauthn-2/
- IETF RFC 9700 / BCP 240 — Best Current Practice for OAuth 2.0 Security (January 2025): https://www.rfc-editor.org/rfc/rfc9700.txt
- IETF RFC 7636 — Proof Key for Code Exchange by OAuth Public Clients (PKCE): https://www.rfc-editor.org/rfc/rfc7636.txt
- IETF RFC 9449 — OAuth 2.0 Demonstrating Proof of Possession (DPoP): https://www.rfc-editor.org/rfc/rfc9449.txt
- IETF RFC 9126 — OAuth 2.0 Pushed Authorization Requests (PAR): https://www.rfc-editor.org/rfc/rfc9126.txt
- IETF RFC 9207 — OAuth 2.0 Authorization Server Issuer Identification (
iss): https://www.rfc-editor.org/rfc/rfc9207.txt - IETF RFC 9068 — JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens (
at+jwt): https://www.rfc-editor.org/rfc/rfc9068.txt - IETF RFC 8725 / BCP 225 — JSON Web Token Best Current Practices: https://www.rfc-editor.org/rfc/rfc8725.txt