Authorization Support (Using ASP.NET Core Native AuthN/AuthZ Integration) (#377)
This commit is contained in:
parent
cd8e5d5f7f
commit
cdf88e7f5d
6 changed files with 4207 additions and 126 deletions
|
|
@ -0,0 +1,17 @@
|
|||
namespace ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Default values used by MCP authentication.
|
||||
/// </summary>
|
||||
public static class McpAuthenticationDefaults
|
||||
{
|
||||
/// <summary>
|
||||
/// The default value used for authentication scheme name.
|
||||
/// </summary>
|
||||
public const string AuthenticationScheme = "McpAuth";
|
||||
|
||||
/// <summary>
|
||||
/// The default value used for authentication scheme display name.
|
||||
/// </summary>
|
||||
public const string DisplayName = "MCP Authentication";
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
namespace ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the authentication events for Model Context Protocol.
|
||||
/// </summary>
|
||||
public class McpAuthenticationEvents
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the function that is invoked when resource metadata is requested.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This function is called when a resource metadata request is made to the protected resource metadata endpoint.
|
||||
/// The implementer should set the <see cref="ResourceMetadataRequestContext.ResourceMetadata"/> property
|
||||
/// to provide the appropriate metadata for the current request.
|
||||
/// </remarks>
|
||||
public Func<ResourceMetadataRequestContext, Task> OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
using Microsoft.AspNetCore.Authentication;
|
||||
using ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for adding MCP authorization support to ASP.NET Core applications.
|
||||
/// </summary>
|
||||
public static class McpAuthenticationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds MCP authorization support to the application.
|
||||
/// </summary>
|
||||
/// <param name="builder">The authentication builder.</param>
|
||||
/// <param name="configureOptions">An action to configure MCP authentication options.</param>
|
||||
/// <returns>The authentication builder for chaining.</returns>
|
||||
public static AuthenticationBuilder AddMcp(
|
||||
this AuthenticationBuilder builder,
|
||||
Action<McpAuthenticationOptions>? configureOptions = null)
|
||||
{
|
||||
return AddMcp(
|
||||
builder,
|
||||
McpAuthenticationDefaults.AuthenticationScheme,
|
||||
McpAuthenticationDefaults.DisplayName,
|
||||
configureOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds MCP authorization support to the application with a custom scheme name.
|
||||
/// </summary>
|
||||
/// <param name="builder">The authentication builder.</param>
|
||||
/// <param name="authenticationScheme">The authentication scheme name to use.</param>
|
||||
/// <param name="displayName">The display name for the authentication scheme.</param>
|
||||
/// <param name="configureOptions">An action to configure MCP authentication options.</param>
|
||||
/// <returns>The authentication builder for chaining.</returns>
|
||||
public static AuthenticationBuilder AddMcp(
|
||||
this AuthenticationBuilder builder,
|
||||
string authenticationScheme,
|
||||
string displayName,
|
||||
Action<McpAuthenticationOptions>? configureOptions = null)
|
||||
{
|
||||
return builder.AddScheme<McpAuthenticationOptions, McpAuthenticationHandler>(
|
||||
authenticationScheme,
|
||||
displayName,
|
||||
configureOptions);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ModelContextProtocol.Authentication;
|
||||
using System.Text.Encodings.Web;
|
||||
|
||||
namespace ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication handler for MCP protocol that adds resource metadata to challenge responses
|
||||
/// and handles resource metadata endpoint requests.
|
||||
/// </summary>
|
||||
public class McpAuthenticationHandler : AuthenticationHandler<McpAuthenticationOptions>, IAuthenticationRequestHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="McpAuthenticationHandler"/> class.
|
||||
/// </summary>
|
||||
public McpAuthenticationHandler(
|
||||
IOptionsMonitor<McpAuthenticationOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
{
|
||||
// For relative URIs, it's just the path component.
|
||||
expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;
|
||||
}
|
||||
|
||||
// If the path doesn't match, let the request continue through the pipeline
|
||||
if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var cancellationToken = Request.HttpContext.RequestAborted;
|
||||
await HandleResourceMetadataRequestAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the base URL from the current request, including scheme, host, and path base.
|
||||
/// </summary>
|
||||
private string GetBaseUrl() => $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the absolute URI for the resource metadata endpoint.
|
||||
/// </summary>
|
||||
private string GetAbsoluteResourceMetadataUri()
|
||||
{
|
||||
var resourceMetadataUri = Options.ResourceMetadataUri;
|
||||
|
||||
string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;
|
||||
|
||||
if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)
|
||||
{
|
||||
return currentPath;
|
||||
}
|
||||
|
||||
// For relative URIs, combine with the base URL
|
||||
string baseUrl = GetBaseUrl();
|
||||
string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;
|
||||
|
||||
if (!Uri.TryCreate($"{baseUrl.TrimEnd('/')}/{relativePath}", UriKind.Absolute, out var absoluteUri))
|
||||
{
|
||||
throw new InvalidOperationException($"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}");
|
||||
}
|
||||
|
||||
return absoluteUri.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the resource metadata request.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">A token to cancel the operation.</param>
|
||||
private async Task HandleResourceMetadataRequestAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var resourceMetadata = Options.ResourceMetadata;
|
||||
|
||||
if (Options.Events.OnResourceMetadataRequest is not null)
|
||||
{
|
||||
var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)
|
||||
{
|
||||
ResourceMetadata = CloneResourceMetadata(resourceMetadata),
|
||||
};
|
||||
|
||||
await Options.Events.OnResourceMetadataRequest(context);
|
||||
}
|
||||
|
||||
|
||||
if (resourceMetadata == null)
|
||||
{
|
||||
throw new InvalidOperationException("ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata.");
|
||||
}
|
||||
|
||||
await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
// If no forwarding is configured, this handler doesn't perform authentication
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() => AuthenticateResult.NoResult();
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
// Get the absolute URI for the resource metadata
|
||||
string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();
|
||||
|
||||
properties ??= new AuthenticationProperties();
|
||||
|
||||
// Store the resource_metadata in properties in case other handlers need it
|
||||
properties.Items["resource_metadata"] = rawPrmDocumentUri;
|
||||
|
||||
// Add the WWW-Authenticate header with Bearer scheme and resource metadata
|
||||
string headerValue = $"Bearer realm=\"{Scheme.Name}\", resource_metadata=\"{rawPrmDocumentUri}\"";
|
||||
Response.Headers.Append("WWW-Authenticate", headerValue);
|
||||
|
||||
return base.HandleChallengeAsync(properties);
|
||||
}
|
||||
|
||||
internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)
|
||||
{
|
||||
if (resourceMetadata is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ProtectedResourceMetadata
|
||||
{
|
||||
Resource = resourceMetadata.Resource,
|
||||
AuthorizationServers = [.. resourceMetadata.AuthorizationServers],
|
||||
BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],
|
||||
ScopesSupported = [.. resourceMetadata.ScopesSupported],
|
||||
JwksUri = resourceMetadata.JwksUri,
|
||||
ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,
|
||||
ResourceName = resourceMetadata.ResourceName,
|
||||
ResourceDocumentation = resourceMetadata.ResourceDocumentation,
|
||||
ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,
|
||||
ResourceTosUri = resourceMetadata.ResourceTosUri,
|
||||
TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,
|
||||
AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,
|
||||
DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,
|
||||
DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
using Microsoft.AspNetCore.Authentication;
|
||||
using ModelContextProtocol.Authentication;
|
||||
|
||||
namespace ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Options for the MCP authentication handler.
|
||||
/// </summary>
|
||||
public class McpAuthenticationOptions : AuthenticationSchemeOptions
|
||||
{
|
||||
private static readonly Uri DefaultResourceMetadataUri = new("/.well-known/oauth-protected-resource", UriKind.Relative);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="McpAuthenticationOptions"/> class.
|
||||
/// </summary>
|
||||
public McpAuthenticationOptions()
|
||||
{
|
||||
// "Bearer" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.
|
||||
ForwardAuthenticate = "Bearer";
|
||||
ResourceMetadataUri = DefaultResourceMetadataUri;
|
||||
Events = new McpAuthenticationEvents();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the events used to handle authentication events.
|
||||
/// </summary>
|
||||
public new McpAuthenticationEvents Events
|
||||
{
|
||||
get { return (McpAuthenticationEvents)base.Events!; }
|
||||
set { base.Events = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The URI to the resource metadata document.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This URI will be included in the WWW-Authenticate header when a 401 response is returned.
|
||||
/// </remarks>
|
||||
public Uri ResourceMetadataUri { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the protected resource metadata.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This contains the OAuth metadata for the protected resource, including authorization servers,
|
||||
/// supported scopes, and other information needed for clients to authenticate.
|
||||
/// </remarks>
|
||||
public ProtectedResourceMetadata? ResourceMetadata { get; set; }
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using ModelContextProtocol.Authentication;
|
||||
|
||||
namespace ModelContextProtocol.AspNetCore.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Context for resource metadata request events.
|
||||
/// </summary>
|
||||
public class ResourceMetadataRequestContext : HandleRequestContext<McpAuthenticationOptions>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ResourceMetadataRequestContext"/> class.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context.</param>
|
||||
/// <param name="scheme">The authentication scheme.</param>
|
||||
/// <param name="options">The authentication options.</param>
|
||||
public ResourceMetadataRequestContext(
|
||||
HttpContext context,
|
||||
AuthenticationScheme scheme,
|
||||
McpAuthenticationOptions options)
|
||||
: base(context, scheme, options)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the protected resource metadata for the current request.
|
||||
/// </summary>
|
||||
public ProtectedResourceMetadata? ResourceMetadata { get; set; }
|
||||
}
|
||||
Loading…
Reference in a new issue