Repository navigation
[P13] oauth: DPoP-bound tokens (RFC 9449, SEP-1932) - #358
Merged
Merged
Conversation
Adds opt-in DPoP (RFC 9449) to `OAuthAuthorizer`. With `OAuthConfiguration.dpop` set, every token request carries an ES256 DPoP proof, a `DPoP` token is stored with the key's thumbprint and presented as `Authorization: DPoP <token>` with a per-request proof that includes `ath`, and `use_dpop_nonce` errors from the authorization server and the MCP server are retried once per request with the server's nonce; that retry does not count against `maxAuthorizationAttempts`. A `DPoP-Nonce` in any MCP server response is stored for the origin the request went to, through the new `HTTPClientAuthorizer.didReceiveResponse(headers:for:)`. The key is any `DPoPSigningKey`, including a Secure Enclave key. To sign the method and URL, `HTTPClientAuthorizer.authorizationHeader(for:)` is replaced by `authorizationHeaders(for:method:)` (breaking), which the transport applies after `requestModifier`. The fixture handles `auth/dpop` and `auth/dpop-nonce`; the default-leg client baseline goes from 8 to 0 entries.
- Treat a resource server's use_dpop_nonce as the free nonce retry only when the 401 carries a DPoP-Nonce header (RFC 9449 section 9). Without it the authorizer runs a full challenge flow, which now counts against maxAuthorizationAttempts. - authorizationHeaders discards a stored token for another authorization server or another DPoP key only if storage still holds that token, so a token a concurrent challenge saved after the load is kept. - Document that DPoPSigningKey signs synchronously for every MCP and token request while the transport waits, so a key behind a network call slows every request.
- After a refresh, the stored token keeps the previous refresh token when the response has none (RFC 6749 section 6), so a later 401 can refresh again instead of clearing the tokens and starting a new grant. When neither the refresh request nor the response names a scope, the token keeps the scopes granted before (section 6); when the request named one, an omitted response scope still means the requested one (section 5.1).
HTTPClientTransport decided by itself whether a 401 was a DPoP use_dpop_nonce challenge (RFC 9449 §9), the one retry per request that does not count against maxAuthorizationAttempts. It read the challenge with a fresh DefaultOAuthWWWAuthenticateParser, while OAuthAuthorizer reads it with its injected challengeParser, so with a custom parser the two could disagree. The HTTPClientAuthorizer requirement handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:), new in this release, now returns HTTPChallengeResult: whether to retry, and whether the retry is a DPoP nonce retry. Its default calls the Bool handleChallenge (unchanged since 0.12) and classifies the challenge with the default parser as the transport did, so custom authorizers keep their behaviour. OAuthAuthorizer reports the nonce retry it already detects with its challengeParser: a valid DPoP-bound token and a nonce. A use_dpop_nonce it answers with a new token is an ordinary attempt. The transport asks the authorizer first, so it now also calls it for a second nonce challenge before failing the request. The GET stream keeps counting every challenge through an internal Bool overload until it gets the nonce exemption.
- Of a Bearer and a DPoP challenge in one WWW-Authenticate, the authorizer answers the one for the scheme the request used, read from sentAuthorization (the stored token for the Bool method). RFC 9449 section 7.2: a resource that offers both schemes puts the error in the challenge of the mechanism the client used, so a DPoP token's 403 insufficient_scope carried in the DPoP challenge was read from the bare Bearer one and not stepped up. A resource_metadata missing from the answered challenge is taken from the other (RFC 9728 section 5.1). - authorizationHeaders discards a token bound to another DPoP key, or a DPoP token without DPoP, before the expiry check, so an expired one is cleared too, and a refresh never uses the refresh token of such a token: RFC 9449 section 5 has a public client present a proof of the key the refresh token was obtained with. The refresh guard covers prepareAuthorization, which runs before authorizationHeaders. - A use_dpop_nonce challenge is a nonce retry only while the stored DPoP token is bound to the configured key. - Tests: a DPoP token refresh keeps the key binding and sends a proof of that key; the refresh that keeps the previous refresh token also keeps the previously granted, non-empty scopes.
This was referenced Nov 25, 2026
Base automatically changed from
conformance/p12-enterprise-auth
to
rel/1.0.0
November 25, 2026 12:40
canarik
approved these changes
Nov 25, 2026
This was referenced Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P12 (#359) · next: P14 (#357))conformance/p13-dpopconformance/p12-enterprise-auth(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)0679427oauth: DPoP-bound tokens (RFC 9449, SEP-1932)7e18ecfoauth: review fixes77f5f7doauth: second-pass review fixes9ec738eoauth: let the authorizer report a DPoP nonce retry6cf0325oauth: third-pass review fixes (DPoP)Summary
Adds opt-in DPoP (RFC 9449) to
OAuthAuthorizer. WithOAuthConfiguration.dpopset, everytoken request carries an ES256 DPoP proof, a
DPoPtoken is stored with the key's thumbprintand presented as
Authorization: DPoP <token>with a per-request proof that includesath, anduse_dpop_nonceerrors from the authorization server and the MCP server are retried once perrequest with the server's nonce; that retry does not count against
maxAuthorizationAttempts.This covers POST requests; the GET (SSE) stream gets the same once-per-request exemption in P18 (#353).
A
DPoP-Noncein any MCP server response is stored for the origin the request went to, throughthe new
HTTPClientAuthorizer.didReceiveResponse(headers:for:). The key is anyDPoPSigningKey, including a Secure Enclave key. To sign the method and URL,HTTPClientAuthorizer.authorizationHeader(for:)is replaced byauthorizationHeaders(for:method:)(breaking), which the transport applies after
requestModifier. The fixture handlesauth/dpopand
auth/dpop-nonce; the default-leg client baseline goes from 8 to 0 entries.Motivation
9449 §5), the
DPoPscheme withathon resource requests (§7), and server nonces (§8, §9).auth/dpopandauth/dpop-noncewere the last 8 client entries inconformance/baseline.yml. They are extension scenarios in the default leg and do not counttoward a tier.
Parity with the Python and Go SDKs, as of their releases at the time (Python 2.3, Go 1.8):
auth/dpopandauth/dpop-noncepassChanges
DPoP signer and configuration
Sources/MCP/Base/Authorization/OAuthDPoP.swift(new):DPoPSigningKey(public protocol:publicKey,signature(for:)), with conformances forP256.Signing.PrivateKeyand, where CryptoKit is available,SecureEnclave.P256.Signing.PrivateKey.OAuthConfiguration.DPoP:init(key:)for anyDPoPSigningKey,init(privateKey:)defaulting to a new software key,
keyThumbprint(RFC 7638). The key is stored internallyand not exposed.
DPoPProofSigner: compact JWS with headertypdpop+jwt,algES256, publicjwk(EC P-256x,y); claimsjti(16 random bytes),htm,htu(scheme and hostlowercased, no user information, query or fragment),
iat,ath(base64url SHA-256 ofthe token) when a token is presented,
noncewhen one is stored. Nonces are keyed byserver kind (authorization server or resource server) and origin (scheme, host, port),
behind an
NSLock.Sources/MCP/Base/Authorization/OAuthConfiguration.swift:public var dpop: DPoP?and thedpop:initializer parameter.Sources/MCP/Base/Authorization/OAuthModels.swift: PRMdpop_bound_access_tokens_requiredand AS
dpop_signing_alg_values_supporteddecoded;OAuthAccessToken.keyThumbprintandisDPoPBound.Sources/MCP/Base/Authorization/OAuthConstants.swift:use_dpop_nonceerror code,DPoPtoken type.
Sources/MCP/Base/Authorization/OAuthErrors.swift:dpopRequired,dpopAlgorithmUnsupported(supported:).Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift:HTTPHeaderName.dpop,HTTPHeaderName.dpopNonce.Token endpoint
Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift: internalOAuthTokenRequesting.request(parameters:endpoint:authentication:dpop:session:). With asigner, the request carries a
DPoPproof forPOSTto the token endpoint, and anyDPoP-Nonceresponse header is stored for that origin. A 400use_dpop_noncewith a nonce isretried once.
token_typeDPoPis accepted only when the request carried a proof; otherwiseonly
Beareris accepted, as before.Authorizer
Sources/MCP/Base/Authorization/OAuthAuthorizer.swift:HTTPClientAuthorizer.authorizationHeaders(for:method:) throws -> [String: String]replaces
authorizationHeader(for:).OAuthAuthorizerreturnsAuthorization: Bearerfora Bearer token; for a DPoP-bound token,
Authorization: DPoPand aDPoPproof withath.A DPoP-bound token whose thumbprint differs from the configured key's, or any DPoP-bound
token when
dpopisnil, is cleared from storage.token requests. The SEP-990 token exchange at the IdP carries no proof.
storeTokenResponsestorestokenTypeDPoPandkeyThumbprintfor aDPoPanswer; aBeareranswer is stored and used as Bearer.checkDPoPSupport, before registration and the grant: withdpop, an ASdpop_signing_alg_values_supportedwithoutES256throwsdpopAlgorithmUnsupported;without
dpop, PRMdpop_bound_access_tokens_required: truethrowsdpopRequired.handleChallengeparses theBearerchallenge, else theDPoPone. Withdpop, it storesthe
DPoP-Noncefor the MCP server's origin; a 401DPoPchallenge witherror="use_dpop_nonce", a nonce, and a valid DPoP-bound token stored returnstruewithout acquiring a new token.
Sources/MCP/Base/Authorization/OAuthWWWAuthenticateParser.swift: requirementparseChallenge(scheme:from:)with a default implementation;DefaultOAuthWWWAuthenticateParsergeneralized from
Bearerto any scheme.Transport
Sources/MCP/Base/Transports/HTTPClientTransport.swift:applyAuthorization(to:)runs afterrequestModifierfor POST and the SSE GET, with the request's final URL and method. A thrownerror becomes
MCPError.internalError("Authorization flow failed: …"). The call sits before the#if os(Linux)branch, so both send paths use it. The resumption GET of a POST response stream(P1 ([P1] http: deliver related messages on the request's stream; resume client response streams #370)) uses it too.
use_dpop_noncechallenge is retried once perrequest. Before it, such challenges counted against
maxAuthorizationAttempts(3), so a serverthat kept asking for a new nonce got two retries. The transport detects the challenge with
DefaultOAuthWWWAuthenticateParser(401,DPoPscheme,error="use_dpop_nonce"); a secondone for the same request fails it with the mapped authentication error. The token endpoint
already retried once.
Conformance fixture and baseline
conformance/everything-client/main.swift: caseauth/dpop,auth/dpop-nonce:.authorizationCode,.none(clientID: ""),dpop: .init().conformance/baseline.yml: the 8 client entries removed;client: [].Docs and snippets
Examples/Snippets/Protocol/Authorization.swift: snippetauth-dpop.docs/src/protocol.src.md: request step 2 describes the DPoP headers; new "DPoP" section. TheaccessTokenProvider, issuer-check and error paragraphs move ahead of "Enterprise-managedauthorization" (text unchanged).
design/auth.md: protocol signature, transport order,dpopsetting, 401 step 0, section"DPoP (RFC 9449, SEP-1932)", two rejected alternatives, open questions.
docs/src/migration.src.md:HTTPClientAuthorizerandOAuthWWWAuthenticateParsingrows andsection;
OAuthAuthorizationErrornow six new cases in the release;OAuthAccessToken.keyThumbprint;DPoPchallenge parsing under behavior changes; new-features row.docs/src/rough_edges.src.md: DPoP limits (ES256 only, nonces in successful responses).docs/src/troubleshooting.src.md: rows fordpopRequired,dpopAlgorithmUnsupported, arepeated
use_dpop_nonce,tokenResponseInvalid; a note on keys lost across relaunches.ROADMAP.md: DPoP row in the implemented table; "Deferred" renamed "Planned", now tasks only,with the SEP-2663 scope for a later PR; default-leg baseline 25 / 0.
rough_edges.src.mdalsolists the 2025-11-25 experimental tasks (SEP-1686) as not planned.
docs/*.md: regenerated byscripts/weave.swift.CLAUDE.md: DPoP and the header order in the authorization paragraph.MockTokenClientand two call sites inOAuthIssuerTests.swiftandOAuthJWTBearerTests.swiftadapted to the new signatures.Review fixes
Nonces (
OAuthAuthorizer.swift,HTTPClientTransport.swift)DPoP-Noncewas read only inhandleChallenge(401/403) and stored for theconfigured endpoint, while proofs look nonces up by the request's final URL; a nonce rotated in
a 2xx response was never read. New
HTTPClientAuthorizer.didReceiveResponse(headers:for:)(default: nothing). The transport calls it for every response, on both POST paths and for the
GET stream, with the URL the request was sent to, before challenge handling.
OAuthAuthorizerstores the nonce for that origin.
use_dpop_nonceretry counted againstmaxAuthorizationAttempts. The nonce retry no longercounts; a second nonce challenge for the same request fails it. The authorizer says which retry
is a nonce retry:
handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:), newin this release, returns
HTTPChallengeResult(retry,isDPoPNonceRetry).OAuthAuthorizerclassifies with its own
challengeParser; the default implementation keeps the transport'sprevious classification for custom authorizers.
Signing key (
OAuthDPoP.swift)OAuthConfiguration.DPoPexposed the private key as a publicprivateKeyproperty and onlytook a software key. New public protocol
DPoPSigningKey, conformed to byP256.Signing.PrivateKeyandSecureEnclave.P256.Signing.PrivateKey; newinit(key:). Thekey is now the internal
key;privateKeyis removed.init(privateKey:)stays.htukept user information (user:password@). It is now dropped; a URL without validcomponents throws
invalidResourceURIinstead of being used as is.Token response (
OAuthModels.swift,OAuthTokenEndpointClient.swift)token_typewas trimmed for the acceptance check but stored as received, so a paddedDPoPanswer was accepted and not stored as DPoP-bound.
OAuthTokenResponsetrims it when decoding;the endpoint client uses the decoded value.
Docs
docs/src/protocol.src.md,design/auth.md,docs/src/migration.src.md(new-features row),CLAUDE.md, theauth-dpopsnippet comment: nonces from every response, the uncountednonce retry,
DPoPSigningKeyand Secure Enclave keys,htuwithout user information.docs/src/rough_edges.src.md: the DPoP row lists only ES256;design/auth.mddrops theopen question on nonces in successful responses.
docs/*.mdregenerated.Diagram
sequenceDiagram participant C as Client participant AZ as Authorization server participant RS as MCP server Note over C,AZ: discovery, AS must list ES256 if it lists DPoP algorithms C->>AZ: POST token with DPoP proof (htm POST, htu token endpoint, no ath) AZ-->>C: 400 use_dpop_nonce, DPoP-Nonce n1 C->>AZ: POST token with a new proof, nonce n1 AZ-->>C: 200 token_type DPoP Note over C: store token with tokenType DPoP and keyThumbprint C->>RS: POST with Authorization DPoP token and DPoP proof with ath RS-->>C: 401 DPoP challenge use_dpop_nonce, DPoP-Nonce n2 Note over C: keep the token, store n2 for the RS origin C->>RS: POST with Authorization DPoP token and a new proof with ath and n2 RS-->>C: 200API changes
Added:
OAuthConfiguration.DPoPwithinit(key:),init(privateKey:),keyThumbprintDPoPSigningKey(publicKey,signature(for:)), and conformances ofP256.Signing.PrivateKeyand, where CryptoKit is available,SecureEnclave.P256.Signing.PrivateKeyOAuthConfiguration.dpop, and thedpop:initializer parameter (defaulted, afterassertionProvider:)OAuthAccessToken.keyThumbprint, thekeyThumbprint:initializer parameter (defaulted), andOAuthAccessToken.isDPoPBoundOAuthAuthorizationError.dpopRequired,OAuthAuthorizationError.dpopAlgorithmUnsupported(supported:)HTTPHeaderName.dpop,HTTPHeaderName.dpopNonceOAuthWWWAuthenticateParsing.parseChallenge(scheme:from:), with a default implementation;DefaultOAuthWWWAuthenticateParser.parseChallenge(scheme:from:)HTTPClientAuthorizer.authorizationHeaders(for:method:),OAuthAuthorizer.authorizationHeaders(for:method:)HTTPClientAuthorizer.didReceiveResponse(headers:for:), with a default implementation thatdoes nothing;
OAuthAuthorizer.didReceiveResponse(headers:for:)Changed:
breaking: custom
HTTPClientAuthorizerconformances must implementauthorizationHeaders(for:method:) throws -> [String: String]. Return["Authorization": value]where the old method returnedvalue, and[:]fornil.breaking (source):
OAuthAuthorizationErrorhas two new cases.OAuthAccessToken.tokenTypecan now be"DPoP".OAuthAccessTokenhas a new optional storedproperty; tokens encoded by the previous release decode with
keyThumbprint == nil.OAuthWWWAuthenticateParsinghas a new requirement; the default implementation keepsexisting conformances compiling.
HTTPClientAuthorizerhas a new requirement,didReceiveResponse(headers:for:); the defaultimplementation keeps existing conformances compiling.
Removed:
HTTPClientAuthorizer.authorizationHeader(for:)andOAuthAuthorizer.authorizationHeader(for:).Behavior changes
requestModifier(before:before it). An
Authorizationheader set by the modifier is replaced when the authorizerreturns one. The authorizer receives the request's final URL and method, not the configured
endpoint.
authorizationHeadersfails the request withMCPError.internalError("Authorization flow failed: …").dpop: aDPoPchallenge is read forresource_metadata,scopeanderrorwhenthe response has no
Bearerchallenge; a stored DPoP-bound token is discarded; a resourcewith
dpop_bound_access_tokens_required: truefails withdpopRequired. Token endpointbehavior is unchanged.
dpop: everything in Changes above. Tokens fromaccessTokenProviderare always Bearer.didReceiveResponsewiththe request URL. A
use_dpop_noncechallenge from the MCP server is retried once per requestand does not count against
maxAuthorizationAttempts; a second one for the same request failsthe request once
handleChallengereports it as a nonce retry again, instead of being retriedup to
maxAuthorizationAttempts. AnOAuthAuthorizerthat answersuse_dpop_noncewith a newtoken uses up an attempt.
Conformance
--spec-version 2025-11-25--spec-version 2026-07-28Tier score: 100% for client and server at 2025-11-25 and 2026-07-28, unchanged.
auth/dpopauth/dpop-nonceBaseline entries removed:
auth/dpop:sep-1932-client-dpop-auth-scheme,auth/dpop:sep-1932-client-fresh-proof,auth/dpop:sep-1932-client-token-request-proof,auth/dpop-nonce:sep-1932-client-as-nonce,auth/dpop-nonce:sep-1932-client-dpop-auth-scheme,auth/dpop-nonce:sep-1932-client-fresh-proof,auth/dpop-nonce:sep-1932-client-rs-nonce,auth/dpop-nonce:sep-1932-client-token-request-proof. The remaining 25 server entries are thetasks-*extension scenarios.Tests
Tests/MCPTests/OAuthDPoPTests.swift(new, 25 tests):DPoPProofTests: proof is an ES256dpop+jwtsigned by the key in itsjwkheader; newjtiper proof, no
athon token request proofs; nonces per origin and per server kind; RFC 7638thumbprint;
DPoPchallenge parsed alongsideBearer.DPoPAuthorizerTests:DPoPscheme with a proof for the request; stored token records thethumbprint;
Beareranswer used as Bearer with no proof; token bound to another key discarded;DPoP-bound token discarded without
dpop; resourceuse_dpop_noncekeeps the token and thenext proof carries the nonce;
use_dpop_noncewithout a token acquires one;dpopRequired;dpopAlgorithmUnsupported.DPoPTokenRequestTests: proof forPOSTto the token endpoint;use_dpop_nonceretried oncewith the nonce; a second
use_dpop_noncefails; aDPoPtoken for a request without a proofis invalid.
DPoPTransportTests: headers set afterrequestModifier, for the final URL and method; aresource server's
use_dpop_nonceis retried once per request (an authorizer that acceptsevery challenge,
maxAuthorizationAttempts5, a server that always answers with a new nonce:two requests, then an error).
DPoPProofTests:htudrops user information; a customDPoPSigningKeysigns the proofand gives the thumbprint.
DPoPAuthorizerTests: a nonce passed todidReceiveResponseis used for the request URL'sorigin only; a padded
token_type(" DPoP\n") is decoded asDPoPand stored DPoP-bound.DPoPTransportTests: the second nonce challenge fails the request after the authorizer sees it,and every response reaches
didReceiveResponse; withmaxAuthorizationAttempts2, a noncechallenge followed by an
invalid_tokenchallenge still succeeds.Examples/Tests/ProtocolSnippetTests.swift:dpopConfigurationSignsProofs.860 swift-testing tests pass, plus XCTest.
Review notes
tokens, which only the application can do (rejected alternative in
design/auth.md). Thedefault
DPoP()key lives as long as the configuration.dpop, aBeareranswer from the token endpoint is accepted and used asBearer. The client does not refuse it, even when the resource metadata sets
dpop_bound_access_tokens_required.authorizationHeadersclears a DPoP-bound token whosekeyThumbprintdiffersfrom the configured key's. Tokens saved by the previous release (
Bearer, no thumbprint) keepworking as Bearer.
(
retriedWithNonce); for the MCP server,OAuthAuthorizeris shared by concurrent requestsand
operationKeyis only the JSON-RPC method, so the per-request count lives in thetransport's retry loop. The nonce retry does not count against
maxAuthorizationAttempts(3).
DPoP-Noncefrom any response,including 200. On the MCP server side,
didReceiveResponsestores it from every response, forthe origin of the URL the request was sent to (after
requestModifier), so a nonce rotated ina successful response (RFC 9449 §8.2) is used by the next request.
dpop_signing_alg_values_supportedisused with ES256; one that publishes a list without ES256 fails with
dpopAlgorithmUnsupported.htudrops user information, query and fragment and lowercases scheme and host. The signatureis the raw
r‖sform, as forprivate_key_jwt.authorizationHeadersstays synchronous; makingOAuthAuthorizeran actor would make itasync(open question indesign/auth.md).ROADMAP.md"Planned" section with the tasks(SEP-2663) scope, and the SEP-1686 row in
rough_edges.md.DPoPTokenRequestTestsandDPoPTransportTestsare compiled only under#if swift(>=6.1) && !os(Linux). Linux not verified.Verification
Every branch of the stack builds and passes
swift test; on this branch, 853 swift-testingtests plus XCTest. DocC builds with
--warnings-as-errors. All conformance legs pass at theirbaselines; the tier score is 100% for client and server at 2025-11-25 and 2026-07-28.
AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.