Conversation
sivaraman-krishnan
left a comment
There was a problem hiding this comment.
Thanks for putting this together, @goutamadwant. It's a careful piece of work: separate S256 PKCE on each leg, exact redirect matching, the browser-binding cookie checked before the transaction is consumed, iss on the authorization response, and refresh-family replay detection are all things I'd want to see in a proxy like this, and the docs are upfront about the security boundary.
I went through it with Entra in mind, since that's the motivating case in #1446, and checked the store the PR ships and Entra's live discovery metadata. A few things came up.
Setup failures
- The bundled
DistributedCacheMcpOAuthProxyStoreturns a cache miss into a 500.IDistributedCache.GetAsyncreturns a nullbyte[], which converts to an emptyReadOnlyMemory<byte>?withHasValue == true.McpOAuthProxyProtectedStorethen callsUnprotecton zero bytes and throws. So with this store,/authorizewith an unknown (well-formed)client_idreturns 500, and a code exchange that would issue a proxy refresh handle fails after the code has been consumed, because therevoked-refresh-familylookup misses. An app store like the Redis one in the docs isn't affected as long as it returns a real null. The tests useRecordingStore, which does, so they don't hit this. Inline comment has a fix. - The docs' Entra example can't get through discovery. The domain-form issuer (
contoso.onmicrosoft.com/v2.0) resolves to metadata whoseissueris the tenant-GUID form, soSameIssuerfails. With the GUID issuer, it then fails the PKCE check, because Entra's v2.0 metadata doesn't includecode_challenge_methods_supported. Either way/authorizeredirects withserver_error. SettingUpstreamAuthorizationEndpoint/UpstreamTokenEndpointexplicitly avoids both checks. The proxy treats a missing field as "no PKCE", which is RFC 8414's rule (here applied to an OIDC discovery document), even though Entra's authorize endpoint accepts S256. Could the Entra example use explicit endpoints, or the GUID issuer plus an opt-in for upstreams whose S256 support has been checked separately?
Security design
3. Per-client consent. All dynamic clients share one upstream app registration, so the upstream consent screen (or a silent SSO session) is about that app, not the MCP client that started the flow. That's the confused-deputy setup the MCP security best practices describe, so consent for each client has to come from the proxy side. AuthorizationValidator can check app-side approvals, but it can only return bool, and false always becomes access_denied on the client's redirect URI, so it can't show a consent page and resume the request. Would you consider letting the policy return a challenge (for example a redirect to an app consent page plus a resumable request reference), or documenting how an app is expected to provide that flow? An approval recorded for the current user and client_id, tied to the approved redirect URI, scopes and resource, seems like a reasonable shape.
4. resource is optional. If the client omits resource, the AllowedResources check and the audience comparison in MintTokenAsync are both skipped, so the factory-reported audience only has to be non-blank, and isn't checked against AllowedResources. Since MCP clients are required to send resource, requiring it (or defaulting to the single allowed value) and always checking the factory's audience against the resolved resource seems safer.
Correctness
5. A successful upstream refresh can be thrown away. If the upstream response's scope includes anything not requested, ResolveGrantedScopes returns null and the handler returns invalid_grant. The refresh record and family were already taken and aren't restored, so the proxy can't retry with that handle and a rotated upstream refresh token is lost. The client has to start a new authorization flow, which may or may not reuse the user's upstream session. The callback rejects the same kind of response with server_error. Some providers return previously consented scopes. Would it work to use the set that was both requested and granted for the downstream access token, keep the refresh grant's scope separate, and decide what an empty intersection should mean? (Entra's .default is a separate case: it expands to concrete permissions, so a literal intersection wouldn't help there.)
6. Redirects on the upstream client. The named HttpClient keeps the default AllowAutoRedirect = true, and a 307/308 re-posts the form body: the code and verifier or the refresh token, plus the client secret with the default client_secret_post. Not likely with a well-behaved provider, but disabling redirects for this client is cheap defense in depth (inline suggestion).
Smaller items
- A client that omits
scopeat registration (RFC 7591 allows it) and later requests a non-empty scope getsinvalid_scope. - On refresh, the new refresh record stores the downstream
grantedScopes, so a narrower refresh permanently narrows what later refreshes can ask for. RFC 6749 §6 says "if a new refresh token is issued, the refresh token scope MUST be identical to that of the refresh token included by the client in the request." - Refresh never re-reads the client record, so it ignores registration expiry. With the defaults (90-day registration, 30-day refresh, counted from the code exchange), a handle issued on day 89 stays usable until about day 119.
- The rate-limiting sample needs
app.UseRateLimiter(); with onlyRequireRateLimiting, nothing is enforced. - Upstream token responses are read with
ResponseHeadersReadand no proxy-imposed size limit or separate body-read deadline. - Tests: a test using
DistributedCacheMcpOAuthProxyStore(miss onGetAsync/TakeAsync, plus a refresh-enabled code exchange) would have caught (1). Separately, I didn't see negative tests for a wrong verifier, a wrongclient_idat the token endpoint, a token-timeredirect_urimismatch, or a disallowed resource.
Happy to help with any of these, including tests for (1) and (2).
| public async ValueTask<ReadOnlyMemory<byte>?> GetAsync(string key, CancellationToken cancellationToken = default) | ||
| { | ||
| ArgumentException.ThrowIfNullOrEmpty(key); | ||
| return await cache.GetAsync(key, cancellationToken).ConfigureAwait(false); |
There was a problem hiding this comment.
cache.GetAsync returns byte[]?, and a null array converts to an empty ReadOnlyMemory<byte> that's then wrapped, so on a miss the result has HasValue == true. I checked this with a small repro. One gotcha: return value is null ? null : value; has the same problem, because the conditional's type is still byte[]. An explicit early return works:
| return await cache.GetAsync(key, cancellationToken).ConfigureAwait(false); | |
| var value = await cache.GetAsync(key, cancellationToken).ConfigureAwait(false); | |
| if (value is null) | |
| { | |
| return null; | |
| } | |
| return value; |
TakeAsync needs the same change: its return value; on a miss has the same issue.
| !Uri.TryCreate(metadata.TokenEndpoint, UriKind.Absolute, out var tokenEndpoint) || | ||
| !McpOAuthProxyUtilities.IsSecureEndpoint(authorizationEndpoint) || | ||
| !McpOAuthProxyUtilities.IsSecureEndpoint(tokenEndpoint) || | ||
| metadata.CodeChallengeMethodsSupported?.Contains("S256", StringComparer.Ordinal) is not true) |
There was a problem hiding this comment.
Once SameIssuer passes (GUID-form issuer), this still throws for Entra, because its v2.0 metadata omits code_challenge_methods_supported even though it supports S256. With the domain-form issuer from the docs, the check fails earlier, at SameIssuer. Treating the omission as "no PKCE" is a reasonable default. An opt-in setting for upstreams whose S256 support has been checked separately might be a good escape hatch, while keeping the issuer check.
| return RedirectError(redirectUri, query["state"], "server_error", "The authorization policy could not evaluate the request."); | ||
| } | ||
|
|
||
| if (!authorizationAllowed) |
There was a problem hiding this comment.
When this returns false, the user always ends up at the client's redirect URI with access_denied, so the validator can approve or deny but can't send the user to a consent page and resume. Since all dynamic clients share the upstream app's consent, it would help to have a way to return a challenge here (see point 3).
| } | ||
|
|
||
| var resource = query["resource"].ToString(); | ||
| if (!string.IsNullOrEmpty(resource) && !_options.AllowedResources.Contains(resource)) |
There was a problem hiding this comment.
With no resource, this check and the audience comparison in MintTokenAsync are both skipped. The factory audience then only has to be non-blank. Could we require resource (or default to the single allowed value) so the audience is always checked against an allowed resource?
| var grantedScopes = ResolveGrantedScopes(requestedScopes, exchange.Token.Scope); | ||
| if (grantedScopes is null) | ||
| { | ||
| return Error(StatusCodes.Status400BadRequest, "invalid_grant", "The upstream authorization server returned an invalid scope grant."); |
There was a problem hiding this comment.
At this point the upstream refresh has succeeded and may have rotated its refresh token, but the family was already taken and isn't restored before returning, so that token is lost (see point 5).
| ArgumentNullException.ThrowIfNull(configureOptions); | ||
|
|
||
| services.AddDataProtection(); | ||
| services.AddHttpClient(HttpClientName); |
There was a problem hiding this comment.
The default handler follows 307/308 and re-posts the form body. That body includes the refresh token or code verifier, and the client secret with client_secret_post. Suggest disabling auto-redirect for this client:
| services.AddHttpClient(HttpClientName); | |
| services.AddHttpClient(HttpClientName) | |
| .ConfigurePrimaryHttpMessageHandler(static () => new SocketsHttpHandler { AllowAutoRedirect = false }); |
|
I pushed |
|
Thanks for the quick turnaround, @goutamadwant!
The proxy tests pass locally on net10.0 (33/33). Two things I noticed while re-reading:
|
Summary
Add an OAuth 2.1 proxy and Dynamic Client Registration facade to
ModelContextProtocol.AspNetCorefor identity providers that do not support DCR.What changed
IMcpOAuthProxyStore.IDistributedCachestore adapter and document the atomic-store requirements for distributed deployments.The change is additive and does not alter existing authentication or transport behavior.
Testing
dotnet restore ModelContextProtocol.slnxdotnet build ModelContextProtocol.slnx --no-restoredotnet test tests/ModelContextProtocol.AspNetCore.Tests/ModelContextProtocol.AspNetCore.Tests.csproj --no-build --no-restore --filter FullyQualifiedName~OAuthdotnet format ModelContextProtocol.slnx --verify-no-changes --no-restore --include src/ModelContextProtocol.AspNetCore/Authentication tests/ModelContextProtocol.AspNetCore.Tests/OAuth/McpOAuthProxyTests.csdotnet docfx docs/docfx.json --warningsAsErrors trueFixes #1446