Skip to content

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

Open
wants to merge 130 commits into
base: main
Choose a base branch
from

Conversation

localden
Copy link
Collaborator

@localden localden commented May 2, 2025

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

using System.Net.Http.Headers;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Types.Authentication;
using ProtectedMCPServer.Tools;

var builder = WebApplication.CreateBuilder(args);

var serverUrl = "http://localhost:7071/";
var tenantId = "a2213e1c-e51e-4304-9a0d-effe57f31655";
var instance = "https://login.microsoftonline.com/";

builder.Services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = $"{instance}{tenantId}/v2.0";
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = "167b4284-3f92-4436-92ed-38b38f83ae08",
        ValidIssuer = $"{instance}{tenantId}/v2.0",
        NameClaimType = "name",
        RoleClaimType = "roles"
    };

    options.MetadataAddress = $"{instance}{tenantId}/v2.0/.well-known/openid-configuration";

    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = context =>
        {
            var name = context.Principal?.Identity?.Name ?? "unknown";
            var email = context.Principal?.FindFirstValue("preferred_username") ?? "unknown";
            Console.WriteLine($"Token validated for: {name} ({email})");
            return Task.CompletedTask;
        },
        OnAuthenticationFailed = context =>
        {
            Console.WriteLine($"Authentication failed: {context.Exception.Message}");
            return Task.CompletedTask;
        },
        OnChallenge = context =>
        {
            Console.WriteLine($"Challenging client to authenticate with Entra ID");
            return Task.CompletedTask;
        }
    };
})
.AddMcp(options =>
{
    options.ResourceMetadataProvider = context => 
    {
        var metadata = new ProtectedResourceMetadata
        {
            BearerMethodsSupported = { "header" },
            ResourceDocumentation = new Uri("https://docs.example.com/api/weather"),
            AuthorizationServers = { new Uri($"{instance}{tenantId}/v2.0") }
        };

        metadata.ScopesSupported.AddRange(new[] {
            "api://167b4284-3f92-4436-92ed-38b38f83ae08/weather.read" 
        });
        
        return metadata;
    };
});

builder.Services.AddAuthorization();

builder.Services.AddHttpContextAccessor();
builder.Services.AddMcpServer()
.WithTools<WeatherTools>()
.WithHttpTransport();

builder.Services.AddSingleton(_ =>
{
    var client = new HttpClient() { BaseAddress = new Uri("https://api.weather.gov") };
    client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("weather-tool", "1.0"));
    return client;
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// Use the default MCP policy name that we've configured
app.MapMcp().RequireAuthorization();

Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
Console.WriteLine($"PRM Document URL: {serverUrl}.well-known/oauth-protected-resource");
Console.WriteLine("Press Ctrl+C to stop the server");

app.Run(serverUrl);

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:

[McpServerTool, Description("Get weather alerts for a US state.")]
public static async Task<string> GetAlerts(
    HttpClient client,
    IHttpContextAccessor httpContextAccessor,
    [Description("The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).")] string state)

Client

using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;

namespace ProtectedMCPClient;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Protected MCP Weather Server");
        Console.WriteLine();

        var serverUrl = "http://localhost:7071/sse";

        var tokenProvider = new BasicOAuthAuthorizationProvider(
            new Uri(serverUrl), 
            clientId: "6ad97b5f-7a7b-413f-8603-7a3517d4adb8",
            redirectUri: new Uri("http://localhost:1179/callback"),
            scopes: ["api://167b4284-3f92-4436-92ed-38b38f83ae08/weather.read"]
        );

        Console.WriteLine();
        Console.WriteLine($"Connecting to weather server at {serverUrl}...");

        try
        {
            var transportOptions = new SseClientTransportOptions
            {
                Endpoint = new Uri(serverUrl),
                Name = "Secure Weather Client"
            };

            var transport = new SseClientTransport(transportOptions, tokenProvider);
            var client = await McpClientFactory.CreateAsync(transport);

            var tools = await client.ListToolsAsync();
            if (tools.Count == 0)
            {
                Console.WriteLine("No tools available on the server.");
                return;
            }

            Console.WriteLine($"Found {tools.Count} tools on the server.");
            Console.WriteLine();

            if (tools.Any(t => t.Name == "GetAlerts"))
            {
                Console.WriteLine("Calling GetAlerts tool...");

                var result = await client.CallToolAsync(
                    "GetAlerts",
                    new Dictionary<string, object?> { { "state", "WA" } }
                );

                Console.WriteLine("Result: " + result.Content[0].Text);
                Console.WriteLine();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"Inner error: {ex.InnerException.Message}");
            }

            #if DEBUG
            Console.WriteLine($"Stack trace: {ex.StackTrace}");
            #endif
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

@localden localden marked this pull request as draft May 2, 2025 06:38
// Copy the request content if present
if (request.Content != null)
{
var contentBytes = await request.Content.ReadAsByteArrayAsync();
Copy link
Contributor

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.

Copy link
Contributor

@halter73 halter73 left a 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?

Comment on lines +96 to +106
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.");
}
Copy link
Contributor

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(
Copy link
Contributor

@halter73 halter73 May 9, 2025

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.

@localden
Copy link
Collaborator Author

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."

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$"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") }
Copy link

@TylerLeonhardt TylerLeonhardt May 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants