-
Notifications
You must be signed in to change notification settings - Fork 277
WIP: Authorization Support (Using ASP.NET Core Native AuthN/AuthZ Integration) #377
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
src/ModelContextProtocol.AspNetCore/Auth/McpAuthorizationExtensions.cs
Outdated
Show resolved
Hide resolved
src/ModelContextProtocol.AspNetCore/Auth/McpAuthorizationExtensions.cs
Outdated
Show resolved
Hide resolved
src/ModelContextProtocol.AspNetCore/Auth/McpAuthorizationExtensions.cs
Outdated
Show resolved
Hide resolved
src/ModelContextProtocol.AspNetCore/Auth/McpAuthorizationExtensions.cs
Outdated
Show resolved
Hide resolved
src/ModelContextProtocol.AspNetCore/Auth/McpAuthenticationResponseMiddlewareExtensions.cs
Outdated
Show resolved
Hide resolved
Co-authored-by: Stephen Halter <[email protected]>
Co-authored-by: Stephen Halter <[email protected]>
…sions.cs Co-authored-by: Stephen Halter <[email protected]>
src/ModelContextProtocol.AspNetCore/Auth/McpAuthorizationExtensions.cs
Outdated
Show resolved
Hide resolved
src/ModelContextProtocol/Protocol/Transport/SseClientTransportOptions.cs
Outdated
Show resolved
Hide resolved
// Copy the request content if present | ||
if (request.Content != null) | ||
{ | ||
var contentBytes = await request.Content.ReadAsByteArrayAsync(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think we should put this retry logic in the DelegatingHandler. And even if we keep the AuthorizationDelegatingHandler, we should make it internal so we can change the implementation later.
Instead, we should instead surface the 401 Unauthorized HttpResponseMessages to the SseClientTransport and then have it call into the IMcpAuthorizationProvider and update the Authorization header before resending the request. That way we don't have to worry about the DelegatingHandler ever getting used with non-replayable request bodies.
I don't care that if ExtractServerSupportedSchemes and the like literally live in SseClientTransport.cs, but it should not be part of a DelegatingHandler. We should try to factor the code to make it clear we are only replaying JsonRpcMessage request bodies that we created ourselves.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks. The main reason for suggesting adding McpAuthenticationEvents now is because it would be technically breaking to add later. But looking at the current state, I think that McpAuthenticationOptions.UseDynamicResourceMetadata(Func<HttpContext, ProtectedResourceMetadata> provider) andFunc<HttpContext, ProtectedResourceMetadata> McpAuthenticationOptions.ProtectedResourceMetadataProvider { get; set; } should be replaced by a Func<RetrieveResourceMetadataContext, Task> McpAuthenticationEvents.RetrieveResourceMetadata { get; set; } event similar to what we have for JwtBearerEvents.OnChallenge.
I think the "Use" in UseDynamicResourceMetadata wrongly implies that it's configuring a pipeline rather than being another way for overriding a Func property. All the other callbacks I can think that you can configure for any other auth handlers are always on WhateverAuthHandlerOptions.Events.Whatever, and not directly on the options type.
I know that unlike JWT's OnChallenge event, this gets called for both the challenge and the /.well-known/oauth-protected resource callback, but I think that's fine. We can also continue to just use the _resourceMetadata field by default when the event doesn't configure RetrieveResourceMetadataContext.ResourceMetadataAddress. We'll just document it. The RetreiveResourceMetadataContext would derive from BaseContext like JwtBearerChallengeContext does, and that exposes the HttpContext plus more like the current scheme name.
The other thing you'll notice about the events pattern that types like JwtBearerEvents follow is that that also have virtual methods you can override to implement events as an alternative to setting the property. We should also do that if we make the McpAuthenticationHandler an unsealed public type, since we should design it to be inherited from if that's the case. The alternative is to make the handler internal and seal that plus the still-public options and event types. This would make the AuthenticationBuilder.AddMcp extension method the only way to add the handler, but I think that's okay. We did just that with the AuthenticationBuilder.AddBearerToken method in the internal BearerTokenHandler (not to be confused with the JwtBearerHandler).
I also wonder if it'd be more consistent to make the ResourceMetadataUri Uri a ResourceMetadataAddress string instead for consistency with the type JwtBearerOptions.MetadataAddress and JwtBearerOptions.Authority. I'm aware these are not precisely the same thing. I'm just talking about it in terms of string vs Uri and consistency. This is much more of a nit, because Uri obviously works. And I think it should still bind from config because Uri implements ISpanParsable or there's a TypeConverter or something like that (although we should verify). But when in Rome
This is a lot of functionality without any new tests yet, but I realize this PR is still in WIP state. It shouldn't be too hard to make sure we properly throw for bad arguments and configuration, but end-to-end testing is obviously more difficult since it'd have to involve and OAuth server. How hard would it be to add a super basic fake OAuth server for testing like this?
src/ModelContextProtocol/Authentication/AuthorizationDelegatingHandler.cs
Outdated
Show resolved
Hide resolved
var (handled, recommendedScheme) = await _credentialProvider.HandleUnauthorizedResponseAsync( | ||
response, | ||
bestSchemeMatch, | ||
cancellationToken).ConfigureAwait(false); | ||
|
||
if (!handled) | ||
{ | ||
throw new McpException( | ||
$"Failed to handle unauthorized response with scheme '{bestSchemeMatch}'. " + | ||
"The authentication provider was unable to process the authentication challenge."); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't love having a handled/Success bool and then just immediately rethrowing. Looking at the BasicOAuthProvider, it just logs any exceptions to the console and returns false. Bubbling up the original exception to the caller would make things much easier to diagnose.
I don't mind wrapping any exceptions thrown by HandleUnauthorizedResponseAsync with another exception containing this message, but the only reason to use something like handled in C# is if there's a chance you don't need to throw at all.
/// <returns>The resource metadata if the resource matches the server, otherwise throws an exception.</returns> | ||
/// <exception cref="InvalidOperationException">Thrown when the response is not a 401, lacks a WWW-Authenticate header, | ||
/// lacks a resource_metadata parameter, the metadata can't be fetched, or the resource URI doesn't match the server URL.</exception> | ||
public async Task<ProtectedResourceMetadata> ExtractProtectedResourceMetadata( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: Move public methods to the top.
But I don't know why this is the public API we're exposing to do OAuth in the client to begin with. I think this should probably be internal, and we should have a public IMcpCredentialProvider that uses this internal method that looks a lot like the current BasicOAuthProvider in the sample accept the part that gets the authorization code should be pluggable. We don't even need a default implementation for that part since we don't want to encourage HttpListener usage.
We should look at making IMcpCredentialProvider look a lot more similar to the typescript-sdk's OAuthClientProvider. Things that are fully dependent on the application's UI framework like string RedirectUri { get; }
which might be a web URL if the client is hosted in an ASP.NET Core app or an "app://" URL for a WPF or MAUI app. That and RedirectToAuthorization(string uri)
should really be the kinds of things the IMcpCredentialProvider is responsible for like typescript's OAuthClientProvider.
I know there was suggestions that the client has to do a lot more validation. I don't have an opinion on that. But whatever we do, we should do as much as we can ourselves and not shirk responsibility for doing things like making the request to the /token endpoint with the appropriate PKCE challenge and leave that up fully to our customers, because it's unnecessary pain for our customers, and at least some our customers are likely to do in incorrectly.
…gHandler.cs Co-authored-by: Stephen Halter <[email protected]>
…Options.cs Co-authored-by: Stephen Halter <[email protected]>
This might not make it in the current PR, but flagging for future use: https://datatracker.ietf.org/doc/html/rfc9728#name-signed-protected-resource-m |
if (serverSchemes.Count > 0) | ||
{ | ||
throw new IOException( | ||
$"The server does not support any of the provided authentication schemes." |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
$"The server does not support any of the provided authentication schemes." | |
$"The server does not support any of the provided authentication schemes." + |
Resource = new Uri("http://localhost"), | ||
BearerMethodsSupported = { "header" }, | ||
ResourceDocumentation = new Uri("https://docs.example.com/api/weather"), | ||
AuthorizationServers = { new Uri($"{instance}{tenantId}/v2.0") } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AuthorizationServers = { new Uri($"{instance}{tenantId}/v2.0") } | |
AuthorizationServers = { new Uri($"{instance}{tenantId}/oauth2/v2.0") } |
shouldn't it be this?
https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols
Implements the authorization flow for clients and servers, per specification. Instead of re-implementing everything from scratch, this follows the suggestions from #349 and uses the native ASP.NET Core constructs to handle post-discovery steps server-side.
Developer experience
Server
HTTP context in tools
.AddHttpContextAccessor
is used to ensure that tools can access the HTTP context (such as the authorization header contents).Tools that want to use the HTTP context will need to amend their signatures to include a reference to
IHttpContextAccessor
, like this:Client