Registry Mirror
Skip to content

Conversation

@goutamadwant

Copy link
Copy Markdown

Summary

Add an OAuth 2.1 proxy and Dynamic Client Registration facade to ModelContextProtocol.AspNetCore for identity providers that do not support DCR.

What changed

  • Add authorization-server metadata, protected-resource metadata, client registration, authorization, callback, and token endpoints.
  • Discover upstream OAuth endpoints through OIDC metadata.
  • Use separate S256 PKCE flows for the client-to-proxy and proxy-to-provider exchanges.
  • Bind authorization transactions to protected, short-lived cookies.
  • Keep upstream access and refresh tokens server-side using Data Protection and IMcpOAuthProxyStore.
  • Require an application token factory and prevent upstream tokens from being returned to MCP clients.
  • Support opaque refresh-token families, replay detection, descendant revocation, and retry-safe rotation.
  • Add registration and authorization policy callbacks for application-specific validation.
  • Emit structured token-mint audit records containing the subject, audience, scopes, client ID, token ID, and mint time.
  • Provide a single-instance IDistributedCache store adapter and document the atomic-store requirements for distributed deployments.
  • Document configuration, storage, key rotation, rate limiting, and security considerations.

The change is additive and does not alter existing authentication or transport behavior.

Testing

  • dotnet restore ModelContextProtocol.slnx
  • dotnet build ModelContextProtocol.slnx --no-restore
  • dotnet test tests/ModelContextProtocol.AspNetCore.Tests/ModelContextProtocol.AspNetCore.Tests.csproj --no-build --no-restore --filter FullyQualifiedName~OAuth
    • 115 tests passed on each of .NET 8, .NET 9, and .NET 10
  • Focused OAuth proxy suite
    • 17 tests passed on each of .NET 8, .NET 9, and .NET 10
  • dotnet format ModelContextProtocol.slnx --verify-no-changes --no-restore --include src/ModelContextProtocol.AspNetCore/Authentication tests/ModelContextProtocol.AspNetCore.Tests/OAuth/McpOAuthProxyTests.cs
  • dotnet docfx docs/docfx.json --warningsAsErrors true
    • 0 warnings and 0 errors

Fixes #1446

@sivaraman-krishnan sivaraman-krishnan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. The bundled DistributedCacheMcpOAuthProxyStore turns a cache miss into a 500. IDistributedCache.GetAsync returns a null byte[], which converts to an empty ReadOnlyMemory<byte>? with HasValue == true. McpOAuthProxyProtectedStore then calls Unprotect on zero bytes and throws. So with this store, /authorize with an unknown (well-formed) client_id returns 500, and a code exchange that would issue a proxy refresh handle fails after the code has been consumed, because the revoked-refresh-family lookup misses. An app store like the Redis one in the docs isn't affected as long as it returns a real null. The tests use RecordingStore, which does, so they don't hit this. Inline comment has a fix.
  2. The docs' Entra example can't get through discovery. The domain-form issuer (contoso.onmicrosoft.com/v2.0) resolves to metadata whose issuer is the tenant-GUID form, so SameIssuer fails. With the GUID issuer, it then fails the PKCE check, because Entra's v2.0 metadata doesn't include code_challenge_methods_supported. Either way /authorize redirects with server_error. Setting UpstreamAuthorizationEndpoint/UpstreamTokenEndpoint explicitly 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 scope at registration (RFC 7591 allows it) and later requests a non-empty scope gets invalid_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 only RequireRateLimiting, nothing is enforced.
  • Upstream token responses are read with ResponseHeadersRead and no proxy-imposed size limit or separate body-read deadline.
  • Tests: a test using DistributedCacheMcpOAuthProxyStore (miss on GetAsync/TakeAsync, plus a refresh-enabled code exchange) would have caught (1). Separately, I didn't see negative tests for a wrong verifier, a wrong client_id at the token endpoint, a token-time redirect_uri mismatch, 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
services.AddHttpClient(HttpClientName);
services.AddHttpClient(HttpClientName)
.ConfigurePrimaryHttpMessageHandler(static () => new SocketsHttpHandler { AllowAutoRedirect = false });

@goutamadwant

Copy link
Copy Markdown
Author

I pushed 4893276a with the cache-miss fix, resource binding, refresh-scope handling, and redirect protection. The Entra example now uses explicit endpoints.

@sivaraman-krishnan

Copy link
Copy Markdown

Thanks for the quick turnaround, @goutamadwant! 4893276a addresses the main points from my review:

  • Store: DistributedCacheMcpOAuthProxyStore now returns a real null on a miss in both GetAsync and TakeAsync, and the new tests use the shipped store, including the initial refresh-family path.
  • Entra: the example now uses explicit tenant endpoints, with the reason spelled out.
  • Consent: documenting the middleware + validator pattern makes the boundary clear: a single-use request reference bound to the user, with AuthorizationValidator re-checking the stored grant. Whether the SDK should eventually offer a built-in challenge result is the maintainers' call.
  • Resource: when resource is omitted, the sole configured resource is used. The token factory's reported audience must match the resolved resource, and a mismatched resource on the code exchange is rejected before the code is consumed.
  • Refresh: the scope intersection now accepts a broader upstream grant and keeps the rotated token, an empty intersection restores the family with the latest upstream refresh token, and a narrower refresh no longer shrinks the stored grant.
  • Upstream client: auto-redirects are off, responses are capped at 1 MiB, and ResponseContentRead means the timeout covers the body.

The proxy tests pass locally on net10.0 (33/33).

Two things I noticed while re-reading:

  1. The new 1 MiB cap can turn a retryable failure into a lost session. With ResponseContentRead, a response body over the cap makes SendAsync throw HttpRequestException (ConfigurationLimitExceeded) before the status code is visible, and that's now classified as non-transient. So a 503/429 from the provider with a large error page returns invalid_grant and drops the refresh family, where before it would have been retried. Reading headers first, classifying retryable statuses, and only then reading the body with a bounded read would keep the cap without changing retry behavior.
  2. Optional, pre-existing: a non-transient upstream refresh failure (for example a 400 from the provider) takes the refresh record and family without restoring them, and the consumed-handle marker stays, so the client has to re-authorize even if the provider didn't consume its refresh token. That may well be the intended fail-closed behavior; it might just be worth a sentence in the docs.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Auth] OAuth proxy / DCR facade for non-DCR providers (e.g. Entra ID + Claude Code)

2 participants