Skip to content

Commit 7369a26

Browse files
Enforce PKCE metadata compliance in OAuth client (#730) (#1700)
1 parent 71d7eea commit 7369a26

3 files changed

Lines changed: 230 additions & 10 deletions

File tree

‎src/ModelContextProtocol.Core/Authentication/ClientOAuthProvider.cs‎

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -366,8 +366,15 @@ static bool IsValidClientMetadataDocumentUri(Uri uri)
366366

367367
private async Task<AuthorizationServerMetadata> GetAuthServerMetadataAsync(Uri authServerUri, string? resourceUri, CancellationToken cancellationToken)
368368
{
369+
// Tracks whether at least one well-known endpoint returned a structurally valid metadata document.
370+
// This distinguishes "no metadata document was found" (eligible for the 2025-03-26 legacy fallback)
371+
// from "a metadata document exists but failed PKCE validation" (must not fall back to synthesized defaults).
372+
var metadataDocumentFound = false;
373+
McpException? pkceValidationFailure = null;
374+
369375
foreach (var wellKnownEndpoint in GetWellKnownAuthorizationServerMetadataUris(authServerUri))
370376
{
377+
AuthorizationServerMetadata? metadata;
371378
try
372379
{
373380
var response = await _httpClient.GetAsync(wellKnownEndpoint, cancellationToken).ConfigureAwait(false);
@@ -377,7 +384,7 @@ private async Task<AuthorizationServerMetadata> GetAuthServerMetadataAsync(Uri a
377384
}
378385

379386
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
380-
var metadata = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.AuthorizationServerMetadata, cancellationToken).ConfigureAwait(false);
387+
metadata = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.AuthorizationServerMetadata, cancellationToken).ConfigureAwait(false);
381388

382389
if (metadata is null)
383390
{
@@ -395,23 +402,63 @@ private async Task<AuthorizationServerMetadata> GetAuthServerMetadataAsync(Uri a
395402
ThrowFailedToHandleUnauthorizedResponse($"AuthorizationEndpoint must use HTTP or HTTPS. '{metadata.AuthorizationEndpoint}' does not meet this requirement.");
396403
}
397404

398-
metadata.ResponseTypesSupported ??= ["code"];
399-
metadata.GrantTypesSupported ??= ["authorization_code", "refresh_token"];
400-
metadata.TokenEndpointAuthMethodsSupported ??= ["client_secret_post"];
401-
metadata.CodeChallengeMethodsSupported ??= ["S256"];
402-
403-
return metadata;
405+
// A structurally valid metadata document was discovered. Even if it fails PKCE validation
406+
// below, its existence disqualifies the legacy fallback that would otherwise synthesize S256.
407+
metadataDocumentFound = true;
404408
}
405409
catch (Exception ex)
406410
{
407411
LogErrorFetchingAuthServerMetadata(ex, wellKnownEndpoint);
412+
continue;
413+
}
414+
415+
try
416+
{
417+
// Per the MCP spec, clients MUST verify PKCE support via authorization server metadata and refuse
418+
// to proceed without it. Rather than failing on the first document that lacks it, skip to the next
419+
// discovery endpoint: different well-known endpoints (OAuth 2.0 vs OpenID Connect) can return
420+
// different documents for the same server, and OpenID Connect metadata commonly includes the field.
421+
var codeChallengeMethods = metadata.CodeChallengeMethodsSupported;
422+
if (codeChallengeMethods is null)
423+
{
424+
ThrowFailedToHandleUnauthorizedResponse(
425+
$"Authorization server metadata from '{wellKnownEndpoint}' does not include 'code_challenge_methods_supported'. MCP clients require PKCE support and must refuse to proceed.");
426+
}
427+
428+
if (!codeChallengeMethods.Contains("S256"))
429+
{
430+
var advertisedMethods = codeChallengeMethods.Count > 0
431+
? string.Join(", ", codeChallengeMethods)
432+
: "<none>";
433+
ThrowFailedToHandleUnauthorizedResponse(
434+
$"Authorization server metadata from '{wellKnownEndpoint}' does not advertise required PKCE method 'S256' in 'code_challenge_methods_supported'. Advertised methods: {advertisedMethods}.");
435+
}
436+
}
437+
catch (Exception ex)
438+
{
439+
LogAuthServerMetadataMissingPkceSupport(ex, wellKnownEndpoint);
440+
pkceValidationFailure = ex as McpException ?? new McpException(ex.Message, ex);
441+
continue;
408442
}
443+
444+
metadata.ResponseTypesSupported ??= ["code"];
445+
metadata.GrantTypesSupported ??= ["authorization_code", "refresh_token"];
446+
metadata.TokenEndpointAuthMethodsSupported ??= ["client_secret_post"];
447+
448+
return metadata;
449+
}
450+
451+
// A discovered metadata document that failed PKCE validation must not be replaced with synthesized
452+
// defaults. Surface the specific PKCE failure regardless of whether PRM was available.
453+
if (metadataDocumentFound && pkceValidationFailure is not null)
454+
{
455+
throw pkceValidationFailure;
409456
}
410457

411458
if (resourceUri is null)
412459
{
413-
// 2025-03-26 backcompat: when PRM is unavailable and auth server metadata discovery
414-
// also fails, fall back to default endpoint paths per the 2025-03-26 spec.
460+
// 2025-03-26 backcompat: when PRM is unavailable and no auth server metadata document was
461+
// discovered, fall back to default endpoint paths per the 2025-03-26 spec.
415462
return BuildDefaultAuthServerMetadata(authServerUri);
416463
}
417464

@@ -1155,6 +1202,9 @@ private static void ThrowFailedToHandleUnauthorizedResponse(string message) =>
11551202
[LoggerMessage(Level = LogLevel.Error, Message = "Error fetching auth server metadata from {Endpoint}")]
11561203
partial void LogErrorFetchingAuthServerMetadata(Exception ex, Uri endpoint);
11571204

1205+
[LoggerMessage(Level = LogLevel.Warning, Message = "Authorization server metadata from {Endpoint} does not satisfy PKCE requirements; skipping it and trying the next discovery endpoint.")]
1206+
partial void LogAuthServerMetadataMissingPkceSupport(Exception ex, Uri endpoint);
1207+
11581208
[LoggerMessage(Level = LogLevel.Information, Message = "Performing dynamic client registration with {RegistrationEndpoint}")]
11591209
partial void LogPerformingDynamicClientRegistration(Uri registrationEndpoint);
11601210

‎tests/ModelContextProtocol.AspNetCore.Tests/OAuth/AuthTests.cs‎

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,85 @@ public async Task CanAuthenticate_WithClientMetadataDocument()
131131
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
132132
}
133133

134+
[Fact]
135+
public async Task CannotAuthenticate_WhenMetadataOmitsPkceMethods()
136+
{
137+
TestOAuthServer.CodeChallengeMethodsSupported = null;
138+
await using var app = await StartMcpServerAsync();
139+
140+
await using var transport = new HttpClientTransport(new()
141+
{
142+
Endpoint = new(McpServerUrl),
143+
OAuth = new()
144+
{
145+
ClientId = "demo-client",
146+
ClientSecret = "demo-secret",
147+
RedirectUri = new Uri("http://localhost:1179/callback"),
148+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
149+
},
150+
}, HttpClient, LoggerFactory);
151+
152+
await Assert.ThrowsAsync<McpException>(() => McpClient.CreateAsync(
153+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
154+
155+
// No discovery endpoint advertises PKCE, so metadata discovery is exhausted. The precise PKCE reason
156+
// is logged as each endpoint is skipped.
157+
Assert.Contains(
158+
MockLoggerProvider.LogMessages,
159+
m => m.Exception?.Message.Contains("code_challenge_methods_supported") == true);
160+
}
161+
162+
[Fact]
163+
public async Task CannotAuthenticate_WhenMetadataLacksS256PkceMethod()
164+
{
165+
TestOAuthServer.CodeChallengeMethodsSupported = ["plain"];
166+
await using var app = await StartMcpServerAsync();
167+
168+
await using var transport = new HttpClientTransport(new()
169+
{
170+
Endpoint = new(McpServerUrl),
171+
OAuth = new()
172+
{
173+
ClientId = "demo-client",
174+
ClientSecret = "demo-secret",
175+
RedirectUri = new Uri("http://localhost:1179/callback"),
176+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
177+
},
178+
}, HttpClient, LoggerFactory);
179+
180+
await Assert.ThrowsAsync<McpException>(() => McpClient.CreateAsync(
181+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
182+
183+
Assert.Contains(
184+
MockLoggerProvider.LogMessages,
185+
m => m.Exception?.Message.Contains("required PKCE method 'S256'") == true);
186+
}
187+
188+
[Fact]
189+
public async Task CanAuthenticate_WhenFirstMetadataEndpointOmitsPkce_ButAnotherAdvertisesIt()
190+
{
191+
// The OAuth 2.0 authorization server metadata endpoint is tried before the OpenID Connect one.
192+
// Simulate a server where only the OpenID Connect document advertises PKCE support, and verify the
193+
// client falls through to it rather than failing on the first PKCE-less document.
194+
TestOAuthServer.MetadataPathsWithoutPkceSupport.Add("/.well-known/oauth-authorization-server");
195+
await using var app = await StartMcpServerAsync();
196+
197+
await using var transport = new HttpClientTransport(new()
198+
{
199+
Endpoint = new(McpServerUrl),
200+
OAuth = new()
201+
{
202+
ClientId = "demo-client",
203+
ClientSecret = "demo-secret",
204+
RedirectUri = new Uri("http://localhost:1179/callback"),
205+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
206+
},
207+
}, HttpClient, LoggerFactory);
208+
209+
await using var client = await McpClient.CreateAsync(
210+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
211+
}
212+
134213
[Fact]
135214
public async Task UsesDynamicClientRegistration_WhenCimdNotSupported()
136215
{
@@ -1671,6 +1750,81 @@ public async Task CanAuthenticate_WithLegacyServerUsingDefaultEndpointFallback()
16711750
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
16721751
}
16731752

1753+
[Fact]
1754+
public async Task CannotAuthenticate_WithLegacyServerWhoseMetadataOmitsPkceMethods()
1755+
{
1756+
// 2025-03-26 backcompat regression guard: PRM is unavailable (resourceUri is null), but the server
1757+
// DOES serve an auth server metadata document that omits 'code_challenge_methods_supported'.
1758+
// The client must refuse to proceed rather than falling back to synthesized S256 defaults, since a
1759+
// discovered metadata document that fails PKCE validation disqualifies the legacy default fallback.
1760+
TestOAuthServer.ExpectResource = false;
1761+
1762+
// Use JwtBearer as the challenge scheme so the 401 response does NOT include resource_metadata.
1763+
Builder.Services.Configure<AuthenticationOptions>(options => options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme);
1764+
1765+
Builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
1766+
{
1767+
options.TokenValidationParameters.ValidateAudience = false;
1768+
});
1769+
1770+
await using var app = Builder.Build();
1771+
1772+
app.Use(async (context, next) =>
1773+
{
1774+
// Return 404 for PRM to simulate a legacy server that doesn't support RFC 9728.
1775+
if (context.Request.Path.StartsWithSegments("/.well-known/oauth-protected-resource"))
1776+
{
1777+
context.Response.StatusCode = StatusCodes.Status404NotFound;
1778+
return;
1779+
}
1780+
1781+
// Serve auth server metadata that omits 'code_challenge_methods_supported' entirely.
1782+
if (context.Request.Path.StartsWithSegments("/.well-known/oauth-authorization-server") ||
1783+
context.Request.Path.StartsWithSegments("/.well-known/openid-configuration"))
1784+
{
1785+
context.Response.ContentType = "application/json";
1786+
await context.Response.WriteAsync($$"""
1787+
{
1788+
"issuer": "{{OAuthServerUrl}}",
1789+
"authorization_endpoint": "{{McpServerUrl}}/authorize",
1790+
"token_endpoint": "{{McpServerUrl}}/token",
1791+
"registration_endpoint": "{{McpServerUrl}}/register",
1792+
"response_types_supported": ["code"],
1793+
"grant_types_supported": ["authorization_code", "refresh_token"],
1794+
"token_endpoint_auth_methods_supported": ["client_secret_post"]
1795+
}
1796+
""");
1797+
return;
1798+
}
1799+
1800+
await next();
1801+
});
1802+
1803+
app.UseAuthentication();
1804+
app.UseAuthorization();
1805+
app.MapMcp().RequireAuthorization();
1806+
await app.StartAsync(TestContext.Current.CancellationToken);
1807+
1808+
await using var transport = new HttpClientTransport(new()
1809+
{
1810+
Endpoint = new(McpServerUrl),
1811+
OAuth = new()
1812+
{
1813+
ClientId = "demo-client",
1814+
ClientSecret = "demo-secret",
1815+
RedirectUri = new Uri("http://localhost:1179/callback"),
1816+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
1817+
},
1818+
}, HttpClient, LoggerFactory);
1819+
1820+
var ex = await Assert.ThrowsAsync<McpException>(() => McpClient.CreateAsync(
1821+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
1822+
1823+
// The specific PKCE failure reason is surfaced rather than a generic discovery failure or a
1824+
// silently-synthesized S256 fallback.
1825+
Assert.Contains("code_challenge_methods_supported", ex.Message);
1826+
}
1827+
16741828
[Fact]
16751829
public async Task AuthorizationFlow_AppendsOfflineAccess_WhenServerAdvertisesIt()
16761830
{

‎tests/ModelContextProtocol.TestOAuthServer/Program.cs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,20 @@ public Program(ILoggerProvider? loggerProvider = null, IConnectionListenerFactor
100100
/// </remarks>
101101
public bool IncludeOfflineAccessInMetadata { get; set; }
102102

103+
/// <summary>
104+
/// Gets or sets the code challenge methods advertised by metadata endpoints.
105+
/// </summary>
106+
/// <remarks>
107+
/// The default value is <c>["S256"]</c>.
108+
/// </remarks>
109+
public List<string>? CodeChallengeMethodsSupported { get; set; } = ["S256"];
110+
111+
/// <summary>
112+
/// Gets the set of metadata paths that should omit <c>code_challenge_methods_supported</c> from their
113+
/// response, simulating a server whose discovery endpoints advertise differing PKCE support.
114+
/// </summary>
115+
public HashSet<string> MetadataPathsWithoutPkceSupport { get; } = new(StringComparer.OrdinalIgnoreCase);
116+
103117
public HashSet<string> DisabledMetadataPaths { get; } = new(StringComparer.OrdinalIgnoreCase);
104118
public IReadOnlyCollection<string> MetadataRequests => _metadataRequests.ToArray();
105119

@@ -237,7 +251,9 @@ IResult HandleMetadataRequest(HttpContext context, string? issuerPath = null)
237251
: ["openid", "profile", "email", "mcp:tools"],
238252
TokenEndpointAuthMethodsSupported = ["client_secret_post"],
239253
ClaimsSupported = ["sub", "iss", "name", "email", "aud"],
240-
CodeChallengeMethodsSupported = ["S256"],
254+
CodeChallengeMethodsSupported = MetadataPathsWithoutPkceSupport.Contains(context.Request.Path)
255+
? null
256+
: CodeChallengeMethodsSupported,
241257
GrantTypesSupported = ["authorization_code", "refresh_token"],
242258
IntrospectionEndpoint = $"{_url}/introspect",
243259
RegistrationEndpoint = $"{_url}/register",

0 commit comments

Comments
 (0)