Skip to content

Commit 616a464

Browse files
remikeholczerhalter73
authored andcommitted
Allow setting token endpoint auth method on ClientOAuthOptions (modelcontextprotocol#1612)
Add ClientOAuthOptions.TokenEndpointAuthMethod to override the token_endpoint_auth_method otherwise inferred from DCR or the server's advertised methods. Needed for CIMD public clients that must use "none" even when the server advertises client_secret_basic first (e.g. Auth0). An explicit value now takes precedence over the DCR-returned method.
1 parent 15f8b2d commit 616a464

4 files changed

Lines changed: 81 additions & 2 deletions

File tree

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ public sealed class ClientOAuthOptions
2323
/// </remarks>
2424
public string? ClientSecret { get; set; }
2525

26+
/// <summary>
27+
/// Gets or sets the token endpoint authentication method (<c>token_endpoint_auth_method</c>) to use when
28+
/// requesting tokens, for example <c>"none"</c>, <c>"client_secret_basic"</c>, or <c>"client_secret_post"</c>.
29+
/// </summary>
30+
/// <remarks>
31+
/// When not set, the method is inferred from the dynamic client registration response (when DCR is used), and
32+
/// otherwise from the first entry in the authorization server's <c>token_endpoint_auth_methods_supported</c>.
33+
/// Set this explicitly when that inference is incorrect — most notably for a public client identified by a
34+
/// <see cref="ClientMetadataDocumentUri">Client ID Metadata Document</see>, which must authenticate with
35+
/// <c>"none"</c> (relying on PKCE) even when the authorization server advertises a different method first.
36+
/// </remarks>
37+
public string? TokenEndpointAuthMethod { get; set; }
38+
2639
/// <summary>
2740
/// Gets or sets the HTTPS URL pointing to this client's metadata document.
2841
/// </summary>

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ public ClientOAuthProvider(
100100
_clientId = options.ClientId;
101101
_configuredClientId = options.ClientId;
102102
_clientSecret = options.ClientSecret;
103+
_tokenEndpointAuthMethod = options.TokenEndpointAuthMethod;
103104
_redirectUri = options.RedirectUri ?? throw new ArgumentException("ClientOAuthOptions.RedirectUri must configured.", nameof(options));
104105
_configuredScopes = options.Scopes is null ? null : string.Join(" ", options.Scopes);
105106
_scopeSelector = options.ScopeSelector;
@@ -983,9 +984,11 @@ private async Task PerformDynamicClientRegistrationAsync(
983984
_clientSecret = registrationResponse.ClientSecret;
984985
}
985986

987+
// Honor an explicitly configured ClientOAuthOptions.TokenEndpointAuthMethod over the value returned by
988+
// dynamic client registration.
986989
if (!string.IsNullOrEmpty(registrationResponse.TokenEndpointAuthMethod))
987990
{
988-
_tokenEndpointAuthMethod = registrationResponse.TokenEndpointAuthMethod;
991+
_tokenEndpointAuthMethod ??= registrationResponse.TokenEndpointAuthMethod;
989992
}
990993

991994
LogDynamicClientRegistrationSuccessful(_clientId!);

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

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,59 @@ public async Task CanAuthenticate_WhenFirstMetadataEndpointOmitsPkce_ButAnotherA
439439
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
440440
}
441441

442+
[Fact]
443+
public async Task CannotAuthenticate_WithClientMetadataDocument_WhenServerAdvertisesClientSecretBasicFirst()
444+
{
445+
// Mimic authorization servers (e.g. Auth0) that advertise client_secret_basic ahead of "none".
446+
// A CIMD client is a public client, but without an explicit TokenEndpointAuthMethod the client falls back to
447+
// the first advertised method (client_secret_basic) and authenticates with the client id and an empty secret
448+
// in the Authorization header rather than placing the client id in the body — which a public client cannot
449+
// satisfy, so the token exchange fails.
450+
TestOAuthServer.SupportedTokenEndpointAuthMethods = ["client_secret_basic", "client_secret_post", "none"];
451+
452+
await using var app = await StartMcpServerAsync();
453+
454+
await using var transport = new HttpClientTransport(new()
455+
{
456+
Endpoint = new(McpServerUrl),
457+
OAuth = new ClientOAuthOptions()
458+
{
459+
RedirectUri = new Uri("http://localhost:1179/callback"),
460+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
461+
ClientMetadataDocumentUri = new Uri(ClientMetadataDocumentUrl),
462+
},
463+
}, HttpClient, LoggerFactory);
464+
465+
await Assert.ThrowsAnyAsync<HttpRequestException>(() => McpClient.CreateAsync(
466+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
467+
}
468+
469+
[Fact]
470+
public async Task CanAuthenticate_WithClientMetadataDocument_AndExplicitNoneAuthMethod()
471+
{
472+
// Same Auth0-like server that advertises client_secret_basic first, but the client explicitly declares the
473+
// public-client "none" method. The token request must then carry the client id in the body (no secret) and
474+
// succeed, proving ClientOAuthOptions.TokenEndpointAuthMethod overrides the server-advertised default.
475+
TestOAuthServer.SupportedTokenEndpointAuthMethods = ["client_secret_basic", "client_secret_post", "none"];
476+
477+
await using var app = await StartMcpServerAsync();
478+
479+
await using var transport = new HttpClientTransport(new()
480+
{
481+
Endpoint = new(McpServerUrl),
482+
OAuth = new ClientOAuthOptions()
483+
{
484+
RedirectUri = new Uri("http://localhost:1179/callback"),
485+
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
486+
ClientMetadataDocumentUri = new Uri(ClientMetadataDocumentUrl),
487+
TokenEndpointAuthMethod = "none",
488+
},
489+
}, HttpClient, LoggerFactory);
490+
491+
await using var client = await McpClient.CreateAsync(
492+
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
493+
}
494+
442495
[Fact]
443496
public async Task UsesDynamicClientRegistration_WhenCimdNotSupported()
444497
{

‎tests/ModelContextProtocol.TestOAuthServer/Program.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,16 @@ public Program(ILoggerProvider? loggerProvider = null, IConnectionListenerFactor
135135
/// </summary>
136136
public HashSet<string> MetadataPathsWithoutPkceSupport { get; } = new(StringComparer.OrdinalIgnoreCase);
137137

138+
/// <summary>
139+
/// Gets or sets the authentication methods advertised in the discovery document's
140+
/// <c>token_endpoint_auth_methods_supported</c>. Tests can set this to mimic authorization servers
141+
/// (such as Auth0) that advertise <c>client_secret_basic</c> ahead of <c>none</c>.
142+
/// </summary>
143+
/// <remarks>
144+
/// The default value is <c>["client_secret_post"]</c>.
145+
/// </remarks>
146+
public List<string> SupportedTokenEndpointAuthMethods { get; set; } = ["client_secret_post"];
147+
138148
public HashSet<string> DisabledMetadataPaths { get; } = new(StringComparer.OrdinalIgnoreCase);
139149
public IReadOnlyCollection<string> MetadataRequests => _metadataRequests.ToArray();
140150

@@ -276,7 +286,7 @@ IResult HandleMetadataRequest(HttpContext context, string? issuerPath = null)
276286
ScopesSupported = IncludeOfflineAccessInMetadata
277287
? ["openid", "profile", "email", "mcp:tools", "offline_access"]
278288
: ["openid", "profile", "email", "mcp:tools"],
279-
TokenEndpointAuthMethodsSupported = ["client_secret_post"],
289+
TokenEndpointAuthMethodsSupported = SupportedTokenEndpointAuthMethods,
280290
ClaimsSupported = ["sub", "iss", "name", "email", "aud"],
281291
CodeChallengeMethodsSupported = MetadataPathsWithoutPkceSupport.Contains(context.Request.Path)
282292
? null

0 commit comments

Comments
 (0)