Skip to content

Commit 4aade88

Browse files
authored
Implement RFC 9207 issuer validation in ClientOAuthProvider (#1605)
1 parent 990bd76 commit 4aade88

18 files changed

Lines changed: 707 additions & 149 deletions

File tree

‎docs/list-of-diagnostics.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,4 @@ When APIs are marked as obsolete, a diagnostic is emitted to warn users that the
4545
| `MCP9004` | In place | <xref:ModelContextProtocol.AspNetCore.HttpServerTransportOptions.EnableLegacySse> opts into the legacy SSE transport which has no built-in HTTP-level backpressure. Use Streamable HTTP instead. See [Stateless — Legacy SSE transport](xref:stateless#legacy-sse-transport) for details. |
4646
| `MCP9005` | In place | The Roots, Sampling, and Logging features are deprecated as of specification version 2026-07-28 and may be removed in a future version. See SEP-2577 for more information. |
4747
| `MCP9006` | In place | The stateful Streamable HTTP configuration knobs on <xref:ModelContextProtocol.AspNetCore.HttpServerTransportOptions> — `EventStreamStore`, `SessionMigrationHandler`, `PerSessionExecutionContext`, `IdleTimeout`, and `MaxIdleSessionCount` — only apply when `Stateless = false`. Starting with the `2026-07-28` protocol revision, Streamable HTTP no longer supports sessions, and the SDK now defaults `Stateless` to `true`. These knobs remain available for back-compat with the legacy stateful Streamable HTTP transport but new code should target the stateless path. |
48+
| `MCP9007` | In place | `AuthorizationRedirectDelegate` and `ClientOAuthOptions.AuthorizationRedirectDelegate` are retained for source and binary compatibility but cannot provide the RFC 9207 authorization-response issuer. Use `ClientOAuthOptions.AuthorizationCallbackHandler` for issuer-aware authorization flows. |

‎samples/ProtectedMcpClient/Program.cs‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Microsoft.Extensions.Logging;
2+
using ModelContextProtocol.Authentication;
23
using ModelContextProtocol.Client;
34
using ModelContextProtocol.Protocol;
45
using System.Diagnostics;
@@ -32,7 +33,7 @@
3233
OAuth = new()
3334
{
3435
RedirectUri = new Uri("http://localhost:1179/callback"),
35-
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
36+
AuthorizationCallbackHandler = HandleAuthorizationUrlAsync,
3637
DynamicClientRegistration = new()
3738
{
3839
ClientName = "ProtectedMcpClient",
@@ -68,12 +69,16 @@
6869
/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.
6970
/// This implementation demonstrates how SDK consumers can provide their own authorization flow.
7071
/// </summary>
71-
/// <param name="authorizationUrl">The authorization URL to open in the browser.</param>
72-
/// <param name="redirectUri">The redirect URI where the authorization code will be sent.</param>
72+
/// <param name="authorizationContext">The context containing the authorization and redirect URIs.</param>
7373
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
74-
/// <returns>The authorization code extracted from the callback, or null if the operation failed.</returns>
75-
static async Task<string?> HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)
74+
/// <returns>The authorization result extracted from the callback, or null if the operation failed.</returns>
75+
static async Task<AuthorizationResult?> HandleAuthorizationUrlAsync(
76+
AuthorizationCallbackContext authorizationContext,
77+
CancellationToken cancellationToken)
7678
{
79+
var authorizationUrl = authorizationContext.AuthorizationUri;
80+
var redirectUri = authorizationContext.RedirectUri;
81+
7782
Console.WriteLine("Starting OAuth authorization flow...");
7883
Console.WriteLine($"Opening browser to: {authorizationUrl}");
7984

@@ -93,6 +98,7 @@
9398
var context = await listener.GetContextAsync();
9499
var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);
95100
var code = query["code"];
101+
var iss = query["iss"];
96102
var error = query["error"];
97103

98104
string responseHtml = "<html><body><h1>Authentication complete</h1><p>You can close this window now.</p></body></html>";
@@ -115,7 +121,7 @@
115121
}
116122

117123
Console.WriteLine("Authorization code received successfully.");
118-
return code;
124+
return new AuthorizationResult { Code = code, Iss = iss };
119125
}
120126
catch (Exception ex)
121127
{

‎src/Common/Obsoletions.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,8 @@ internal static class Obsoletions
4646
public const string LegacyStatefulHttp_DiagnosticId = "MCP9006";
4747
public const string LegacyStatefulHttp_Message = "Stateful Streamable HTTP mode is a back-compat-only escape hatch for legacy clients. Set HttpServerTransportOptions.Stateless = true (the default as of the 2026-07-28 protocol revision) for new code. See SEP-2567.";
4848
public const string LegacyStatefulHttp_Url = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#obsolete-apis";
49+
50+
public const string AuthorizationRedirectDelegate_DiagnosticId = "MCP9007";
51+
public const string AuthorizationRedirectDelegate_Message = "AuthorizationRedirectDelegate cannot provide the RFC 9207 issuer and is retained for compatibility only. Use AuthorizationCallbackHandler instead.";
52+
public const string AuthorizationRedirectDelegate_Url = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#obsolete-apis";
4953
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
namespace ModelContextProtocol.Authentication;
2+
3+
/// <summary>
4+
/// Provides the information needed to complete an OAuth authorization request.
5+
/// </summary>
6+
public sealed class AuthorizationCallbackContext
7+
{
8+
/// <summary>
9+
/// Gets the authorization URI that the user needs to visit.
10+
/// </summary>
11+
public required Uri AuthorizationUri { get; init; }
12+
13+
/// <summary>
14+
/// Gets the redirect URI where the authorization response will be sent.
15+
/// </summary>
16+
public required Uri RedirectUri { get; init; }
17+
}
Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-

21
namespace ModelContextProtocol.Authentication;
32

43
/// <summary>
@@ -9,20 +8,13 @@ namespace ModelContextProtocol.Authentication;
98
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
109
/// <returns>A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.</returns>
1110
/// <remarks>
12-
/// <para>
13-
/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.
14-
/// Implementers can choose to:
15-
/// </para>
16-
/// <list type="bullet">
17-
/// <item><description>Start a local HTTP server and open a browser (default behavior)</description></item>
18-
/// <item><description>Display the authorization URL to the user for manual handling</description></item>
19-
/// <item><description>Integrate with a custom UI or authentication flow</description></item>
20-
/// <item><description>Use a different redirect mechanism altogether</description></item>
21-
/// </list>
22-
/// <para>
23-
/// The implementation should handle user interaction to visit the authorization URL and extract
24-
/// the authorization code from the callback. The authorization code is typically provided as
25-
/// a query parameter in the redirect URI callback.
26-
/// </para>
11+
/// This delegate cannot return the <c>iss</c> parameter from the authorization response, so
12+
/// <see href="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</see> issuer validation is
13+
/// skipped when it is used. Use <see cref="ClientOAuthOptions.AuthorizationCallbackHandler"/> for
14+
/// issuer-aware authorization flows.
2715
/// </remarks>
28-
public delegate Task<string?> AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);
16+
[Obsolete(
17+
ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_Message,
18+
DiagnosticId = ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_DiagnosticId,
19+
UrlFormat = ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_Url)]
20+
public delegate Task<string?> AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
namespace ModelContextProtocol.Authentication;
2+
3+
/// <summary>
4+
/// Represents the result of an OAuth authorization redirect, containing the authorization code
5+
/// and optionally the issuer identifier from the authorization response.
6+
/// </summary>
7+
/// <remarks>
8+
/// <para>
9+
/// The <see cref="Iss"/> property should be populated from the <c>iss</c> query parameter in the
10+
/// redirect URI when present, as specified by
11+
/// <see href="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</see>.
12+
/// This enables the SDK to validate that the authorization response originated from the expected
13+
/// authorization server, mitigating mix-up attacks.
14+
/// </para>
15+
/// </remarks>
16+
public sealed class AuthorizationResult
17+
{
18+
/// <summary>
19+
/// Gets the authorization code returned by the authorization server.
20+
/// </summary>
21+
public string? Code { get; init; }
22+
23+
/// <summary>
24+
/// Gets the issuer identifier returned in the authorization response per
25+
/// <see href="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</see>.
26+
/// </summary>
27+
/// <remarks>
28+
/// <para>
29+
/// This value should be extracted from the <c>iss</c> query parameter of the redirect URI.
30+
/// When present, the SDK validates it against the expected authorization server issuer to
31+
/// prevent mix-up attacks.
32+
/// </para>
33+
/// <para>
34+
/// Implementations of <see cref="ClientOAuthOptions.AuthorizationCallbackHandler"/> should populate this
35+
/// property whenever the <c>iss</c> parameter is present in the redirect URI callback.
36+
/// </para>
37+
/// </remarks>
38+
public string? Iss { get; init; }
39+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,11 @@ internal sealed class AuthorizationServerMetadata
7272
/// </summary>
7373
[JsonPropertyName("client_id_metadata_document_supported")]
7474
public bool ClientIdMetadataDocumentSupported { get; set; }
75+
76+
/// <summary>
77+
/// Indicates whether the authorization server includes the <c>iss</c> parameter in authorization responses
78+
/// as defined in <see href="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</see>.
79+
/// </summary>
80+
[JsonPropertyName("authorization_response_iss_parameter_supported")]
81+
public bool AuthorizationResponseIssParameterSupported { get; set; }
7582
}

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

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,44 @@ public sealed class ClientOAuthOptions
7070
public ScopeSelectorDelegate? ScopeSelector { get; set; }
7171

7272
/// <summary>
73-
/// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.
73+
/// Gets or sets the callback that handles the OAuth authorization flow.
7474
/// </summary>
7575
/// <remarks>
7676
/// <para>
77-
/// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.
78-
/// If not specified, a default implementation will be used that prompts the user to enter the code manually.
77+
/// This callback receives the authorization and redirect URIs in an
78+
/// <see cref="AuthorizationCallbackContext"/> and returns the authorization response.
79+
/// If not specified, a default implementation prompts the user to enter the full redirect URL manually.
7980
/// </para>
8081
/// <para>
8182
/// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture
82-
/// the authorization code from the OAuth redirect.
83+
/// the authorization response. They should return both the <c>code</c> and <c>iss</c> query parameters
84+
/// from the redirect URI callback. This enables the SDK to validate the <c>iss</c> parameter per
85+
/// <see href="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</see>, which mitigates
86+
/// mix-up attacks.
87+
/// </para>
88+
/// <para>
89+
/// This property cannot be configured together with <see cref="AuthorizationRedirectDelegate"/>.
90+
/// </para>
91+
/// </remarks>
92+
public Func<AuthorizationCallbackContext, CancellationToken, Task<AuthorizationResult?>>? AuthorizationCallbackHandler { get; set; }
93+
94+
/// <summary>
95+
/// Gets or sets the legacy authorization redirect delegate for handling the OAuth authorization flow.
96+
/// </summary>
97+
/// <remarks>
98+
/// <para>
99+
/// This delegate returns only the authorization code and cannot provide the <c>iss</c> parameter from
100+
/// the authorization response. Consequently, RFC 9207 issuer validation is skipped when this delegate
101+
/// is used. Use <see cref="AuthorizationCallbackHandler"/> for issuer-aware authorization flows.
102+
/// </para>
103+
/// <para>
104+
/// This property cannot be configured together with <see cref="AuthorizationCallbackHandler"/>.
83105
/// </para>
84106
/// </remarks>
107+
[Obsolete(
108+
ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_Message,
109+
DiagnosticId = ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_DiagnosticId,
110+
UrlFormat = ModelContextProtocol.Obsoletions.AuthorizationRedirectDelegate_Url)]
85111
public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }
86112

87113
/// <summary>

0 commit comments

Comments
 (0)