-
Notifications
You must be signed in to change notification settings - Fork 558
Enhance MCP authentication handler to correctly handle absolute URIs for resource metadata endpoint #937
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
Open
sr-auto
wants to merge
2
commits into
modelcontextprotocol:main
Choose a base branch
from
sr-auto:sr/fix_resource_metadata_uri_absolute
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+90
−2
Open
Enhance MCP authentication handler to correctly handle absolute URIs for resource metadata endpoint #937
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ | |
| using ModelContextProtocol.Authentication; | ||
| using ModelContextProtocol.Client; | ||
| using System.Net; | ||
| using System.Net.Http.Json; | ||
| using System.Reflection; | ||
| using Xunit.Sdk; | ||
|
|
||
|
|
@@ -391,6 +392,84 @@ public void CloneResourceMetadataClonesAllProperties() | |
| Assert.Empty(propertyNames); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ResourceMetadataEndpoint_ResolvesCorrectly_WithAbsoluteUriIncludingPathComponent() | ||
| { | ||
| const string enterprisePath = "/enterprise"; | ||
| const string metadataPath = "/.well-known/oauth-protected-resource"; | ||
| const string fullMetadataPath = enterprisePath + metadataPath; | ||
|
|
||
| // Configure the builder with a fresh authentication setup for this test | ||
| var testBuilder = WebApplication.CreateSlimBuilder(); | ||
| testBuilder.Services.AddSingleton(XunitLoggerProvider); | ||
|
|
||
| testBuilder.Services.AddAuthentication(options => | ||
| { | ||
| options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme; | ||
| options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; | ||
| }) | ||
| .AddJwtBearer(options => | ||
| { | ||
| options.Backchannel = HttpClient; | ||
| options.Authority = OAuthServerUrl; | ||
| options.TokenValidationParameters = new TokenValidationParameters | ||
| { | ||
| ValidateIssuer = true, | ||
| ValidateAudience = true, | ||
| ValidateLifetime = true, | ||
| ValidateIssuerSigningKey = true, | ||
| ValidAudience = McpServerUrl, | ||
| ValidIssuer = OAuthServerUrl, | ||
| NameClaimType = "name", | ||
| RoleClaimType = "roles" | ||
| }; | ||
| }) | ||
| .AddMcp(options => | ||
| { | ||
| // Set an absolute URI with a path component after the host | ||
| options.ResourceMetadataUri = new Uri($"{McpServerUrl}{fullMetadataPath}"); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we have a test for a custom relative path? If not, can we add that too? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure. I'll add one in. |
||
| options.ResourceMetadata = new ProtectedResourceMetadata | ||
| { | ||
| Resource = new Uri(McpServerUrl), | ||
| AuthorizationServers = { new Uri(OAuthServerUrl) }, | ||
| ScopesSupported = ["mcp:tools"] | ||
| }; | ||
| }); | ||
|
|
||
| testBuilder.Services.AddAuthorization(); | ||
| testBuilder.Services.AddMcpServer().WithHttpTransport(); | ||
|
|
||
| await using var app = testBuilder.Build(); | ||
|
|
||
| app.MapMcp().RequireAuthorization(); | ||
|
|
||
| await app.StartAsync(TestContext.Current.CancellationToken); | ||
|
|
||
| // Test that the metadata endpoint responds at the correct path with the path component | ||
| var metadataResponse = await HttpClient.GetAsync($"{McpServerUrl}{fullMetadataPath}", TestContext.Current.CancellationToken); | ||
| Assert.Equal(HttpStatusCode.OK, metadataResponse.StatusCode); | ||
|
|
||
| var metadata = await metadataResponse.Content.ReadFromJsonAsync<ProtectedResourceMetadata>( | ||
| McpJsonUtilities.DefaultOptions, TestContext.Current.CancellationToken); | ||
|
|
||
| Assert.NotNull(metadata); | ||
| Assert.Equal(new Uri(McpServerUrl), metadata.Resource); | ||
| Assert.Contains(new Uri(OAuthServerUrl), metadata.AuthorizationServers); | ||
| Assert.Contains("mcp:tools", metadata.ScopesSupported); | ||
|
|
||
| // Test that a request without the path component returns 401 (not the metadata) | ||
| var unauthorizedResponse = await HttpClient.GetAsync($"{McpServerUrl}/message", TestContext.Current.CancellationToken); | ||
| Assert.Equal(HttpStatusCode.Unauthorized, unauthorizedResponse.StatusCode); | ||
|
|
||
| // Verify the WWW-Authenticate header includes the full absolute URI with path component | ||
| var wwwAuthHeader = unauthorizedResponse.Headers.WwwAuthenticate.FirstOrDefault(); | ||
| Assert.NotNull(wwwAuthHeader); | ||
| Assert.Equal("Bearer", wwwAuthHeader.Scheme); | ||
| Assert.Contains($"resource_metadata=\"{McpServerUrl}{fullMetadataPath}\"", wwwAuthHeader.Parameter); | ||
|
|
||
| await app.StopAsync(TestContext.Current.CancellationToken); | ||
| } | ||
|
|
||
| private async Task<string?> HandleAuthorizationUrlAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken) | ||
| { | ||
| _lastAuthorizationUri = authorizationUri; | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
It seems wrong to throw away the host name when it's been explicitly configured. If the app developer configures
AllowedHoststo something other than*, they are already protected against DNS rebinding, but not everyone does that.But if the developer chooses a specific host name for the
ResourceMetadataUri, it seems that we should require it. If the developer doesn't want to require a specific host name for the resource metadata data document, they can use a relative URI.Uh oh!
There was an error while loading. Please reload this page.
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've learned via chat that the motivating reason for using an absolute
ResourceMetadataUriwas to fix the scenario whereGetBaseUrl() => $"{Request.Scheme}://{Request.Host}{Request.PathBase}"gave inaccurate results due to a gateway in front of an app without properly configured forwarded headers. The result was thatcontext.Request.Hostcontained an internal hostname rather than the publicly visible one specified inResourceMetadataUri. Basically, this is exactly the scenario I suggested we reject for having the "wrong" host name.For this scenario, I think using
app.UseForwardedHeaders()and a relativeResourceMetadataUriis the best approach. Configuring forwarded headers could help fix other scenarios involving absolute link generation too.Given that an absolute
ResourceMetadataUrihas never worked, I wonder if the best bet for now is simply to reject absolute URIs by throwing anArgumentExceptionin the setter. If people really do need to have complete control over the absolute URI generated for theWww-Authenticationheader, that could probably be a new configuration and/orMcpAuthenticationEventsthat gets run inHandleChallengeAsync.