Skip to content
Merged
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
42 changes: 42 additions & 0 deletions tests/ModelContextProtocol.AspNetCore.Tests/OAuth/AuthTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
Expand Down Expand Up @@ -527,6 +528,47 @@ await Assert.ThrowsAsync<McpException>(() => McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
}

[Fact]
public async Task CannotAuthenticate_WhenProtectedResourceMetadataMissingResource()
{
TestOAuthServer.RequireResource = false;

Builder.Services.Configure<McpAuthenticationOptions>(McpAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Events.OnResourceMetadataRequest = async context =>
{
context.HandleResponse();

var metadata = new ProtectedResourceMetadata
{
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:tools"],
};

await Results.Json(metadata, McpJsonUtilities.DefaultOptions).ExecuteAsync(context.HttpContext);
};
});

await using var app = await StartMcpServerAsync();

await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "demo-client",
ClientSecret = "demo-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
},
}, HttpClient, LoggerFactory);

var ex = await Assert.ThrowsAsync<McpException>(() => McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));

Assert.Contains("Resource URI in metadata", ex.Message);
}

[Fact]
public async Task CanAuthenticate_WithAuthorizationServerPathInsertionMetadata()
{
Expand Down
12 changes: 10 additions & 2 deletions tests/ModelContextProtocol.TestOAuthServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ public Program(ILoggerProvider? loggerProvider = null, IConnectionListenerFactor
/// </remarks>
public bool ClientIdMetadataDocumentSupported { get; set; } = true;

/// <summary>
/// Gets or sets a value indicating whether the authorization server requires a resource parameter.
/// </summary>
/// <remarks>
/// The default value is <c>true</c>.
/// </remarks>
public bool RequireResource { get; set; } = true;

public HashSet<string> DisabledMetadataPaths { get; } = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyCollection<string> MetadataRequests => _metadataRequests.ToArray();

Expand Down Expand Up @@ -289,7 +297,7 @@ IResult HandleMetadataRequest(HttpContext context, string? issuerPath = null)
}

// Validate resource in accordance with RFC 8707
if (string.IsNullOrEmpty(resource) || !ValidResources.Contains(resource))
if (RequireResource && (string.IsNullOrEmpty(resource) || !ValidResources.Contains(resource)))
{
return Results.Redirect($"{redirect_uri}?error=invalid_target&error_description=The+specified+resource+is+not+valid&state={state}");
}
Expand Down Expand Up @@ -337,7 +345,7 @@ IResult HandleMetadataRequest(HttpContext context, string? issuerPath = null)

// Validate resource in accordance with RFC 8707
var resource = form["resource"].ToString();
if (string.IsNullOrEmpty(resource) || !ValidResources.Contains(resource))
if (RequireResource && (string.IsNullOrEmpty(resource) || !ValidResources.Contains(resource)))
{
return Results.BadRequest(new OAuthErrorResponse
{
Expand Down