Repository navigation
[P12] oauth: jwt-bearer grant, token exchange, enterprise-managed authorization - #359
Merged
Merged
Conversation
…tion Adds the RFC 7523 JWT bearer grant to `OAuthAuthorizer`, an RFC 8693 token exchange client, and a one-call configuration for enterprise-managed authorization (SEP-990). The same grant with a public client covers workload identity federation (SEP-1933). The conformance client fixture drops its hand-written token code and uses the SDK API for `auth/enterprise-managed-authorization` and `auth/wif-jwt-bearer`. The default-leg client baseline goes from 11 to 8 entries. It also sends jwt-bearer assertions only to a configured authorization server unless the caller opts into the discovered one (`allowsDiscoveredAuthorizationServer`), then checks the assertion's audience; it also stops the 2025-03-26 endpoint fallback for this grant, renews tokens without a refresh token before they expire, and discovers the identity provider's token endpoint once.
- Limit proactive renewal: each access token is tried once, so a failed refresh or grant is left to the 401 path instead of being retried before every request; a token issued for less than proactiveRefreshWindowSeconds is renewed halfway through the time it is sent (until the 30 s expiry skew), and one that is never sent is not renewed, so short-lived tokens are not replaced on every request. - With allowsDiscoveredAuthorizationServer and no configured server, refuse an assertion whose aud cannot be read (not a JWT, no aud, no string in an aud array) instead of sending it unchecked; read padded JWT payloads and the string members of a mixed aud array. - Document that endpointOverrides.tokenEndpoint alone fixes where the assertion goes but not the audience asked of the assertion provider, which still comes from discovery; authorizationServerURL fixes both. - Tests that relied on a token shorter than the window being renewed at once now age a stored token into the window; tests that sent a non-JWT assertion to a discovered server send a JWT or pin the server.
- Proactive renewal also runs when only endpointOverrides.tokenEndpoint names the token endpoint: the guard required the authorization server metadata's token_endpoint, which the grants never read when the override is set. Applies to the refresh-token and the jwt-bearer and client_credentials branches. - A proactive renewal cut short by cancellation no longer marks the token as tried, so the next request attempts it again instead of waiting for a 401. - A jwt-bearer grant without a configured authorization server or token endpoint, and without allowsDiscoveredAuthorizationServer, fails with authorizationServerNotConfigured before it fetches the metadata of a server the MCP server named (RFC 7523 §3 audience). Before, discovery ran first: it sent requests to those servers, and its errors hid the configuration error.
- The jwt-bearer grant checks the issuer of a configured authorization server too: its metadata must name endpointOverrides.authorizationServerURL as `issuer` (RFC 8414 §3.3, ID-JAG draft §9.5), or the grant fails with authorizationServerIssuerMismatch before any assertion is made. Before, a configured server was trusted whatever issuer its metadata named, and that issuer became the assertion's audience: enterpriseManaged asked the identity provider for an ID-JAG for it and sent the ID-JAG and the client credentials to the token endpoint the metadata named. Other grants keep trusting a configured server. - A jwt-bearer grant without an assertion provider (and without an accessTokenProvider) fails with assertionProviderMissing before the authorization server metadata is fetched. - Storing a token clears the proactive-renewal mark, so a token that a server issues again with the same value is renewed again before it expires. - enterpriseManaged keeps the identity provider's discovered token endpoint when an exchange is cancelled. - troubleshooting lists authorizationServerNotConfigured and assertionAudienceMismatch; the guides and doc comments say that a configured jwt-bearer server must name itself as issuer. Tests: the pinned-issuer test asserts authorizationServerIssuerMismatch and that nothing goes to the identity provider or the metadata's token endpoint; the missing-provider test pins a server and asserts the case and that no metadata is fetched; new tests cover a reissued token, a cancelled exchange, and a cancelled refresh-token renewal.
This was referenced Nov 25, 2026
canarik
approved these changes
Nov 25, 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: P11 (#360) · next: P13 (#358))conformance/p12-enterprise-authconformance/p11-fixes(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)68e693foauth: jwt-bearer grant, token exchange, enterprise-managed authorization9431917oauth: review fixes47a76d3oauth: second-pass review fixes2b334d1oauth: third-pass review fixesSummary
Adds the RFC 7523 JWT bearer grant to
OAuthAuthorizer, an RFC 8693 token exchange client, and aone-call configuration for enterprise-managed authorization (SEP-990). The same grant with a
public client covers workload identity federation (SEP-1933). The conformance client fixture
drops its hand-written token code and uses the SDK API for
auth/enterprise-managed-authorizationand
auth/wif-jwt-bearer. The default-leg client baseline goes from 11 to 8 entries. A reviewfix sends jwt-bearer assertions only to a configured authorization server unless the caller opts
into the discovered one (
allowsDiscoveredAuthorizationServer), then checks the assertion'saudience; it also stops the 2025-03-26 endpoint fallback for this grant, renews tokens without a
refresh token before they expire, and discovers the identity provider's token endpoint once.
Motivation
enterprise identity provider for an Identity Assertion JWT Authorization Grant (ID-JAG) with an
RFC 8693 token exchange, then presents the ID-JAG to the MCP authorization server with the
RFC 7523 jwt-bearer grant.
jwt-bearer grant, as a public client.
auth/enterprise-managed-authorizationfailed because the fixture still handledthe stale scenario name
auth/cross-app-access-complete-flow, with the token requests writtenby hand in the fixture.
auth/wif-jwt-bearerhad no fixture case;GrantTypehadauthorizationCodeandclientCredentialsonly. Both are extension scenarios in the defaultleg and do not count toward a tier.
Parity with the Python and Go SDKs, as of their releases at the time (Python 2.3, Go 1.8):
IdentityAssertionOAuthProvider(confidential client, configured issuer, no PRM/DCR)extauth.EnterpriseHandlerGrantType.jwtBearer,enterpriseManaged(...)oauthex.ExchangeTokenOAuthTokenExchangePerformOIDCLoginauth/enterprise-managed-authorization.jwtBearerwith a public client, 7/7 checksBefore this PR the SDK matched Python and Go on every scored requirement. This PR closes the
enterprise-auth gap and adds WIF, which neither has.
Changes
Authorizer and configuration
Sources/MCP/Base/Authorization/OAuthConfiguration.swift:GrantType.jwtBearer;AssertionContext(audience,resource,tokenEndpoint,requestedScopes);AssertionProvidertypealias;assertionProviderproperty and initializer parameter.TokenEndpointAuthentication.none(clientID:)no longer writesclient_idwhen the ID is empty.Sources/MCP/Base/Authorization/OAuthAuthorizer.swift:acquireTokenViaJWTBearer. Theassertion audience is the AS metadata
issuer, else the selected authorization server. Thetoken request carries
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer,assertion,resource,scope(when scopes are requested) andadditionalTokenRequestParameters, withthe configured client authentication. Client registration is skipped for
.jwtBearer.Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift:.jwtBearerbranch forexhaustiveness; the authorizer does not register for this grant.
Sources/MCP/Base/Authorization/OAuthConstants.swift: grant type URIs for jwt-bearer andtoken exchange; parameter names
assertion,subject_token,subject_token_type,requested_token_type,audience.Sources/MCP/Base/Authorization/OAuthErrors.swift:assertionProviderMissing,issuedTokenTypeMismatch(expected:actual:).Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift: form encoding moved to aninternal
OAuthFormEncodingenum shared with the token exchange.Token exchange and enterprise-managed authorization
Sources/MCP/Base/Authorization/OAuthTokenExchange.swift(new):OAuthTokenExchange.TokenType:accessToken,refreshToken,idToken,jwt,saml2,idJAG.OAuthTokenExchange.Request,OAuthTokenExchange.Response.OAuthTokenExchange.exchange(_:tokenEndpoint:authentication:session:urlValidator:): formPOST with the RFC 8693 parameters and optional
audience,resource,scope; endpointvalidated as an authorization server URL (
https, or loopbackhttpwhen allowed), privateIP literals rejected, no redirects.
issued_token_typemust equalrequested_token_type;token_typeis not checked (N_Afor an ID-JAG).OAuthTokenExchange.tokenEndpoint(issuer:session:urlValidator:): token endpoint from theissuer's RFC 8414 or OpenID metadata, with the issuer check of AS discovery.
OAuthConfiguration.EnterpriseIdentityProvider(Endpoint.tokenEndpoint(URL)orEndpoint.issuer(URL), clientauthenticationat the IdP),OAuthConfiguration.IDTokenProvider,and
OAuthConfiguration.enterpriseManaged(authentication:authorizationServer:identityProvider:idToken:retryPolicy:additionalTokenRequestParameters:).The returned
.jwtBearerconfiguration's assertion provider asksidTokenfor the ID tokenand runs the exchange with
audience= AS issuer,resource= MCP server and the requestedscopes.
authorizationServersetsendpointOverrides.authorizationServerURL.Conformance fixture and baseline
conformance/everything-client/main.swift: caseauth/cross-app-access-complete-flowreplaced by
auth/enterprise-managed-authorization(enterpriseManaged,authorizationServer: nil,IdP token endpoint and client ID from the harness context) and a new
auth/wif-jwt-bearercase(
.jwtBearer,.none(clientID: ""),context["valid_jwt"]as the assertion). RemovedmakeCrossAppAccessTokenProvider,requestOAuthToken,ConformanceTokenResponseand thefixture's form-encoding helpers.
conformance/baseline.yml: three client entries removed.Docs and snippets
CLAUDE.md: the jwt-bearer grant, token exchange andenterpriseManaged(...)in the authorization paragraph.Examples/Snippets/Protocol/Authorization.swift: snippetsauth-enterprise(pinned AS, IdPby issuer) and
auth-workload-identity; the.none(clientID:)comment now states that anempty ID registers dynamically and any other ID is pre-registered.
docs/src/protocol.src.md:.jwtBearerrow in the grant table; sections "Enterprise-managedauthorization" and "Workload identity".
design/auth.md:assertionProvidersetting; section "JWT bearer grant andenterprise-managed authorization" with a sequence diagram and the Python/Go comparison; open
question for the missing OIDC sign-in helper.
docs/src/migration.src.md:OAuthAuthorizationError(four new cases in total across therelease),
OAuthConfiguration.GrantType; new-features rows for enterprise-managedauthorization and for
StatefulHTTPServerTransport(eventStoreCapacity:)(from the previous PR).docs/src/rough_edges.src.md: enterprise-managed authorization and WIF removed from "Notimplemented"; OIDC sign-in helper listed as not planned.
docs/src/troubleshooting.src.md: rows forassertionProviderMissing,issuedTokenTypeMismatch, andinvalid_grantwith.jwtBearer.ROADMAP.md: three rows in the implemented authorization table; two rows removed from"Deferred"; default-leg baseline 25 / 8.
docs/*.md: regenerated byscripts/weave.swift.Review fixes
Authorizer and configuration (
68e693f;OAuthAuthorizer.swift,OAuthConfiguration.swift,OAuthErrors.swift).jwtBearersent the assertion and theclient credentials to whatever server the MCP server's resource metadata named, so a hostile
MCP server could collect an assertion valid at the real authorization server and replay it.
The grant now needs
endpointOverrides.authorizationServerURLortokenEndpoint; withoutthem it throws
authorizationServerNotConfiguredbefore the assertion provider runs.OAuthConfiguration.allowsDiscoveredAuthorizationServer(initializer parameter, defaultfalse) lets the resource metadata choose the server. Then an assertion that is a JWT with anaudclaim naming neither the discovered issuer nor its token endpoint fails withassertionAudienceMismatch(expected:actual:)before the token request. Assertions that arenot JWTs, or have no
aud, are not checked; a pinned server gets any assertion.applied to every grant.
.jwtBearerno longer uses it.cost a 401 and, for enterprise-managed authorization, both legs on the request path. For
.jwtBearerand.clientCredentials,prepareAuthorizationnow acquires a new token withinproactiveRefreshWindowSecondsof expiry, with the token's scopes; a failure is ignored andthe 401 path recovers.
Token exchange (
OAuthTokenExchange.swift)enterpriseManaged(...)gainsallowsDiscoveredAuthorizationServer: Bool = false, passed tothe configuration; the doc comment says that
authorizationServer: nilneeds it.Endpoint.issuer, the identity provider's metadata was fetched before every exchange.The token endpoint is now discovered once per configuration (lock-protected cache) and
discovered again after a failed exchange.
Fixture, snippets and docs
conformance/everything-client/main.swift: the enterprise-managed and WIF cases passallowsDiscoveredAuthorizationServer: true; the harness names the authorization server only inthe resource metadata.
Examples/Snippets/Protocol/Authorization.swift:auth-workload-identitypinsauthorizationServerURL; the.none(clientID:)comment says that a URL the server does notaccept as a metadata document also registers dynamically.
docs/src/protocol.src.md: the pinning requirement and the opt-in, the audience check, no2025-03-26 fallback for this grant, renewal before expiry, the IdP endpoint read once.
docs/src/migration.src.md: six newOAuthAuthorizationErrorcases across the release.Tests
OAuthJWTBearerTests.swift: new suiteOAuthJWTBearerDestinationTests(6 tests); the existingunpinned tests and the unpinned enterprise configuration set the opt-in.
Diagram
Enterprise-managed authorization (SEP-990):
sequenceDiagram participant App as Client participant IdP as Enterprise IdP participant AZ as MCP authorization server participant RS as MCP server App->>RS: MCP request RS-->>App: 401 Bearer challenge with resource_metadata App->>RS: GET protected resource metadata App->>AZ: GET AS metadata (pinned issuer or from PRM) Note over App: idToken callback returns the ID token App->>IdP: POST token, grant_type token-exchange (RFC 8693) Note right of App: subject_token = ID token, requested_token_type id-jag, audience = AS issuer, resource = MCP server IdP-->>App: 200 access_token = ID-JAG, issued_token_type id-jag App->>AZ: POST token, grant_type jwt-bearer (RFC 7523), assertion = ID-JAG Note right of App: client authentication at the AS, resource, scope AZ-->>App: 200 access_token App->>RS: MCP request with Bearer tokenWorkload identity (SEP-1933):
sequenceDiagram participant W as Workload participant AZ as MCP authorization server participant RS as MCP server W->>RS: MCP request RS-->>W: 401 Bearer challenge W->>AZ: GET AS metadata Note over W: assertionProvider returns the platform-issued JWT W->>AZ: POST token, grant_type jwt-bearer, assertion = workload JWT Note right of W: public client, no client_id, no registration AZ-->>W: 200 access_token W->>RS: MCP request with Bearer tokenAPI changes
Added:
OAuthConfiguration.GrantType.jwtBearerOAuthConfiguration.AssertionContextwithinit(audience:resource:tokenEndpoint:requestedScopes:)OAuthConfiguration.AssertionProviderOAuthConfiguration.assertionProvider, and theassertionProvider:initializer parameter(defaulted, after
accessTokenProvider:)OAuthConfiguration.allowsDiscoveredAuthorizationServer, and theallowsDiscoveredAuthorizationServer:initializer parameter (defaultedfalse, last)OAuthTokenExchange, withTokenType,Request,Response,exchange(_:tokenEndpoint:authentication:session:urlValidator:)andtokenEndpoint(issuer:session:urlValidator:)OAuthConfiguration.EnterpriseIdentityProviderand itsEndpoint(allowsLoopbackHTTPispackage, for the fixture)OAuthConfiguration.IDTokenProviderOAuthConfiguration.enterpriseManaged(authentication:authorizationServer:identityProvider:idToken:retryPolicy:additionalTokenRequestParameters:allowsDiscoveredAuthorizationServer:)OAuthAuthorizationError.assertionProviderMissing,OAuthAuthorizationError.issuedTokenTypeMismatch(expected:actual:),OAuthAuthorizationError.authorizationServerNotConfigured,OAuthAuthorizationError.assertionAudienceMismatch(expected:actual:)Changed:
OAuthConfiguration.GrantTypehas a new case. Exhaustiveswitchstatements need
.jwtBeareror adefault.OAuthAuthorizationErrorhas four new cases. Exhaustiveswitchstatements need them or a
default.Removed: none.
Behavior changes
TokenEndpointAuthentication.none(clientID: "")no longer sends an emptyclient_idformfield.
.jwtBearer: no dynamic client registration; the assertion provider runs for everytoken request (assertions and ID-JAGs are not cached); a failed token request throws
tokenRequestFailedonce, with no retry and no fallback to another grant..jwtBearerwithoutendpointOverrides.authorizationServerURLortokenEndpointfails withauthorizationServerNotConfigured, unlessallowsDiscoveredAuthorizationServeris set; thena JWT assertion for another audience fails with
assertionAudienceMismatchand is not sent.The 2025-03-26 default endpoints are never used for this grant.
enterpriseManagedandauthorizationServer: nil, the authorization server comes fromthe protected resource metadata, and only with
allowsDiscoveredAuthorizationServer: true.With a pinned server, its metadata must name it as
issuer.authorizer also runs them within
proactiveRefreshWindowSeconds(60) of expiry..clientCredentialstokens without a refresh token are also replaced withinproactiveRefreshWindowSecondsof expiry, before the request instead of after a 401.EnterpriseIdentityProvider.Endpoint.issuer, the identity provider's metadata is readonce, and again after a failed exchange.
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/enterprise-managed-authorizationauth/wif-jwt-bearerBaseline entries removed:
auth/enterprise-managed-authorization:complete-flow-jwt-bearer,auth/enterprise-managed-authorization:complete-flow-token-exchange,auth/wif-jwt-bearer:wif-grant-type. The remaining 8 client entries areauth/dpopandauth/dpop-nonce(next PR).Tests
Tests/MCPTests/OAuthJWTBearerTests.swift(new, 20 tests):OAuthJWTBearerGrantTests: token request presents the assertion with resource and scopes;a new assertion per token request; missing provider fails; a provider error fails without a
token request; a pinned authorization server overrides the resource metadata; a rejected
grant (
invalid_grant,invalid_scope,unauthorized_client) is reported once, with noretry and no other grant.
OAuthTokenExchangeTests: RFC 8693 parameters,N_Aaccepted; another issued token typerejected; error responses keep status and OAuth error; insecure and private endpoints refused
before any request; token endpoint discovered from the issuer's metadata.
EnterpriseManagedAuthorizationTests: ID token to ID-JAG to access token end to end; a failedexchange sends no grant; the pinned authorization server must publish metadata with its own
issuer.
OAuthJWTBearerDestinationTests(review fix): without a configured server or the opt-in, noassertion is made or sent; a discovered server gets only an assertion for its issuer or token
endpoint; a configured server gets the assertion whatever its audience; the grant never uses
the 2025-03-26 default endpoints; a token without a refresh token is replaced before it
expires; the identity provider's token endpoint is discovered once.
Examples/Tests/ProtocolSnippetTests.swift:enterpriseAndWorkloadConfigurations.Counts (
swift test, swift-testing): 808 before, 828 after, plus the XCTest suites; all passed.Review notes
.jwtBearersends its assertion only to a configured authorization server bydefault. With
allowsDiscoveredAuthorizationServer: truethe MCP server's resource metadatadecides where the assertion (or ID-JAG) and the client credentials go, limited by the
audcheck. The docs and the
auth-enterpriseandauth-workload-identitysnippets pin it. Thefixture passes
nilwith the opt-in because the harness names the authorization server only inthe resource metadata.
audcheck reads the JWT payload without verifying the signature. It stops a providerthat ignores
context.audiencefrom handing a token meant for another server to thediscovered one: such a provider is refused at a discovered server.
.clientCredentialstoo, which existed before this PR.httpsor allowed loopback, no private IPliteral) before sending and follows no redirects. It does not send a DPoP proof (DPoP is the
next PR).
audclaim, and only for adiscovered server. The WIF assertion provider receives the audience in
AssertionContextandmust return a JWT that is valid for it.
issued_token_typemust equal the requested type;token_typeis not checked.EnterpriseIdentityProvider.allowsLoopbackHTTPispackage, not public; the fixture sets itto reach the harness IdP over loopback
http.PerformOIDCLogin); skipped by decision, listed inrough_edges.md.OAuthTokenExchangeTests,EnterpriseManagedAuthorizationTests,the no-retry test) are compiled only under
#if swift(>=6.1) && !os(Linux). Linux notverified.
Verification
State: the branch builds and passes
swift test(835 swift-testing tests plus the XCTest suites, all passed);swift scripts/weave.swift --checkpasses; DocC builds with--warnings-as-errors; the three conformance legs pass at their baselines, and the tier score is 100% at both revisions.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.