Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,21 @@ public async Task<bool> HandleRequestAsync()
// Check if the request is for the resource metadata endpoint
string requestPath = Request.Path.Value ?? string.Empty;

string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;
if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)
string expectedMetadataPath;
if (Options.ResourceMetadataUri == null)
{
expectedMetadataPath = string.Empty;
}
else if (!Options.ResourceMetadataUri.IsAbsoluteUri)
{
// For relative URIs, it's just the path component.
expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;
}
else
{
// For absolute URIs, extract the path component
expectedMetadataPath = Options.ResourceMetadataUri.AbsolutePath;
Copy link
Contributor

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 AllowedHosts to 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.

Copy link
Contributor

@halter73 halter73 Nov 3, 2025

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 ResourceMetadataUri was to fix the scenario where GetBaseUrl() => $"{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 that context.Request.Host contained an internal hostname rather than the publicly visible one specified in ResourceMetadataUri. 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 relative ResourceMetadataUri is the best approach. Configuring forwarded headers could help fix other scenarios involving absolute link generation too.

Given that an absolute ResourceMetadataUri has never worked, I wonder if the best bet for now is simply to reject absolute URIs by throwing an ArgumentException in the setter. If people really do need to have complete control over the absolute URI generated for the Www-Authentication header, that could probably be a new configuration and/or McpAuthenticationEvents that gets run in HandleChallengeAsync.

}

// If the path doesn't match, let the request continue through the pipeline
if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))
Expand Down
79 changes: 79 additions & 0 deletions tests/ModelContextProtocol.AspNetCore.Tests/AuthTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
using System.Net;
using System.Net.Http.Json;
using System.Reflection;
using Xunit.Sdk;

Expand Down Expand Up @@ -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}");
Copy link
Contributor

Choose a reason for hiding this comment

The 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?

Copy link
Author

Choose a reason for hiding this comment

The 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;
Expand Down