Tokens can be cached beyond the lifetime of the (http) transport. (#834)

This commit is contained in:
Manuel Naujoks 2025-11-25 02:56:56 +01:00 • committed by GitHub
commit 820821fa0c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 538 additions and 373 deletions

View file

@ -86,4 +86,10 @@ public sealed class ClientOAuthOptions
/// </para>
/// </remarks>
public IDictionary<string, string> AdditionalAuthorizationParameters { get; set; } = new Dictionary<string, string>();
/// <summary>
/// Gets or sets the token cache to use for storing and retrieving tokens beyond the lifetime of the transport.
/// If none is provided, tokens will be cached with the transport.
/// </summary>
public ITokenCache? TokenCache { get; set; }
}

View file

@ -13,9 +13,7 @@ using System.Web;
namespace ModelContextProtocol.Authentication;
/// <summary>
/// A generic implementation of an OAuth authorization provider for MCP. This does not do any advanced token
/// protection or caching - it acquires a token and server metadata and holds it in memory.
/// This is suitable for demonstration and development purposes.
/// A generic implementation of an OAuth authorization provider.
/// </summary>
internal sealed partial class ClientOAuthProvider
{
@ -24,6 +22,8 @@ internal sealed partial class ClientOAuthProvider
/// </summary>
private const string BearerScheme = "Bearer";
private static readonly string[] s_wellKnownPaths = [".well-known/openid-configuration", ".well-known/oauth-authorization-server"];
private readonly Uri _serverUrl;
private readonly Uri _redirectUri;
private readonly string[]? _scopes;
@ -43,7 +43,7 @@ internal sealed partial class ClientOAuthProvider
private string? _clientId;
private string? _clientSecret;
private TokenContainer? _token;
private ITokenCache _tokenCache;
private AuthorizationServerMetadata? _authServerMetadata;
/// <summary>
@ -57,11 +57,11 @@ internal sealed partial class ClientOAuthProvider
public ClientOAuthProvider(
Uri serverUrl,
ClientOAuthOptions options,
HttpClient? httpClient = null,
HttpClient httpClient,
ILoggerFactory? loggerFactory = null)
{
_serverUrl = serverUrl ?? throw new ArgumentNullException(nameof(serverUrl));
_httpClient = httpClient ?? new HttpClient();
_httpClient = httpClient;
_logger = (ILogger?)loggerFactory?.CreateLogger<ClientOAuthProvider>() ?? NullLogger.Instance;
if (options is null)
@ -85,6 +85,7 @@ internal sealed partial class ClientOAuthProvider
_dcrClientUri = options.DynamicClientRegistration?.ClientUri;
_dcrInitialAccessToken = options.DynamicClientRegistration?.InitialAccessToken;
_dcrResponseDelegate = options.DynamicClientRegistration?.ResponseDelegate;
_tokenCache = options.TokenCache ?? new InMemoryTokenCache();
}
/// <summary>
@ -138,20 +139,21 @@ internal sealed partial class ClientOAuthProvider
{
ThrowIfNotBearerScheme(scheme);
var tokens = await _tokenCache.GetTokensAsync(cancellationToken).ConfigureAwait(false);
// Return the token if it's valid
if (_token != null && _token.ExpiresAt > DateTimeOffset.UtcNow.AddMinutes(5))
if (tokens is not null && !tokens.IsExpired)
{
return _token.AccessToken;
return tokens.AccessToken;
}
// Try to refresh the token if we have a refresh token
if (_token?.RefreshToken != null && _authServerMetadata != null)
// Try to refresh the access token if it is invalid and we have a refresh token.
if (tokens?.RefreshToken != null && _authServerMetadata != null)
{
var newToken = await RefreshTokenAsync(_token.RefreshToken, resourceUri, _authServerMetadata, cancellationToken).ConfigureAwait(false);
if (newToken != null)
var newTokens = await RefreshTokenAsync(tokens.RefreshToken, resourceUri, _authServerMetadata, cancellationToken).ConfigureAwait(false);
if (newTokens is not null)
{
_token = newToken;
return _token.AccessToken;
return newTokens.AccessToken;
}
}
@ -174,12 +176,7 @@ internal sealed partial class ClientOAuthProvider
HttpResponseMessage response,
CancellationToken cancellationToken = default)
{
// This provider only supports Bearer scheme
if (!string.Equals(scheme, BearerScheme, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This credential provider only supports the Bearer scheme");
}
ThrowIfNotBearerScheme(scheme);
await PerformOAuthAuthorizationAsync(response, cancellationToken).ConfigureAwait(false);
}
@ -223,6 +220,17 @@ internal sealed partial class ClientOAuthProvider
// Store auth server metadata for future refresh operations
_authServerMetadata = authServerMetadata;
// The existing access token must be invalid to have resulted in a 401 response, but refresh might still work.
if (await _tokenCache.GetTokensAsync(cancellationToken).ConfigureAwait(false) is { RefreshToken: {} refreshToken })
{
var refreshedTokens = await RefreshTokenAsync(refreshToken, protectedResourceMetadata.Resource, authServerMetadata, cancellationToken).ConfigureAwait(false);
if (refreshedTokens is not null)
{
// A non-null result indicates the refresh succeeded and the new tokens have been stored.
return;
}
}
// Perform dynamic client registration if needed
if (string.IsNullOrEmpty(_clientId))
{
@ -230,19 +238,11 @@ internal sealed partial class ClientOAuthProvider
}
// Perform the OAuth flow
var token = await InitiateAuthorizationCodeFlowAsync(protectedResourceMetadata, authServerMetadata, cancellationToken).ConfigureAwait(false);
await InitiateAuthorizationCodeFlowAsync(protectedResourceMetadata, authServerMetadata, cancellationToken).ConfigureAwait(false);
if (token is null)
{
ThrowFailedToHandleUnauthorizedResponse($"The {nameof(AuthorizationRedirectDelegate)} returned a null or empty token.");
}
_token = token;
LogOAuthAuthorizationCompleted();
}
private static readonly string[] s_wellKnownPaths = [".well-known/openid-configuration", ".well-known/oauth-authorization-server"];
private async Task<AuthorizationServerMetadata> GetAuthServerMetadataAsync(Uri authServerUri, CancellationToken cancellationToken)
{
if (authServerUri.OriginalString.Length == 0 ||
@ -298,7 +298,7 @@ internal sealed partial class ClientOAuthProvider
throw new McpException($"Failed to find .well-known/openid-configuration or .well-known/oauth-authorization-server metadata for authorization server: '{authServerUri}'");
}
private async Task<TokenContainer> RefreshTokenAsync(string refreshToken, Uri resourceUri, AuthorizationServerMetadata authServerMetadata, CancellationToken cancellationToken)
private async Task<TokenContainer?> RefreshTokenAsync(string refreshToken, Uri resourceUri, AuthorizationServerMetadata authServerMetadata, CancellationToken cancellationToken)
{
var requestContent = new FormUrlEncodedContent(new Dictionary<string, string>
{
@ -314,10 +314,17 @@ internal sealed partial class ClientOAuthProvider
Content = requestContent
};
return await FetchTokenAsync(request, cancellationToken).ConfigureAwait(false);
using var httpResponse = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!httpResponse.IsSuccessStatusCode)
{
return null;
}
return await HandleSuccessfulTokenResponseAsync(httpResponse, cancellationToken).ConfigureAwait(false);
}
private async Task<TokenContainer?> InitiateAuthorizationCodeFlowAsync(
private async Task InitiateAuthorizationCodeFlowAsync(
ProtectedResourceMetadata protectedResourceMetadata,
AuthorizationServerMetadata authServerMetadata,
CancellationToken cancellationToken)
@ -330,10 +337,10 @@ internal sealed partial class ClientOAuthProvider
if (string.IsNullOrEmpty(authCode))
{
return null;
ThrowFailedToHandleUnauthorizedResponse($"The {nameof(AuthorizationRedirectDelegate)} returned a null or empty authorization code.");
}
return await ExchangeCodeForTokenAsync(protectedResourceMetadata, authServerMetadata, authCode!, codeVerifier, cancellationToken).ConfigureAwait(false);
await ExchangeCodeForTokenAsync(protectedResourceMetadata, authServerMetadata, authCode!, codeVerifier, cancellationToken).ConfigureAwait(false);
}
private Uri BuildAuthorizationUrl(
@ -377,7 +384,7 @@ internal sealed partial class ClientOAuthProvider
return uriBuilder.Uri;
}
private async Task<TokenContainer> ExchangeCodeForTokenAsync(
private async Task ExchangeCodeForTokenAsync(
ProtectedResourceMetadata protectedResourceMetadata,
AuthorizationServerMetadata authServerMetadata,
string authorizationCode,
@ -400,24 +407,39 @@ internal sealed partial class ClientOAuthProvider
Content = requestContent
};
return await FetchTokenAsync(request, cancellationToken).ConfigureAwait(false);
}
private async Task<TokenContainer> FetchTokenAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
using var httpResponse = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
httpResponse.EnsureSuccessStatusCode();
await HandleSuccessfulTokenResponseAsync(httpResponse, cancellationToken).ConfigureAwait(false);
}
using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var tokenResponse = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.TokenContainer, cancellationToken).ConfigureAwait(false);
private async Task<TokenContainer> HandleSuccessfulTokenResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken)
{
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var tokenResponse = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.TokenResponse, cancellationToken).ConfigureAwait(false);
if (tokenResponse is null)
{
ThrowFailedToHandleUnauthorizedResponse($"The token endpoint '{request.RequestUri}' returned an empty response.");
ThrowFailedToHandleUnauthorizedResponse($"The token endpoint '{response.RequestMessage?.RequestUri}' returned an empty response.");
}
tokenResponse.ObtainedAt = DateTimeOffset.UtcNow;
return tokenResponse;
if (tokenResponse.TokenType is null || !string.Equals(tokenResponse.TokenType, BearerScheme, StringComparison.OrdinalIgnoreCase))
{
ThrowFailedToHandleUnauthorizedResponse($"The token endpoint '{response.RequestMessage?.RequestUri}' returned an unsupported token type: '{tokenResponse.TokenType ?? "<null>"}'. Only 'Bearer' tokens are supported.");
}
TokenContainer tokens = new()
{
AccessToken = tokenResponse.AccessToken,
RefreshToken = tokenResponse.RefreshToken,
ExpiresIn = tokenResponse.ExpiresIn,
TokenType = tokenResponse.TokenType,
Scope = tokenResponse.Scope,
ObtainedAt = DateTimeOffset.UtcNow,
};
await _tokenCache.StoreTokensAsync(tokens, cancellationToken).ConfigureAwait(false);
return tokens;
}
/// <summary>
@ -581,7 +603,7 @@ internal sealed partial class ClientOAuthProvider
string? resourceMetadataUrl = null;
foreach (var header in response.Headers.WwwAuthenticate)
{
if (string.Equals(header.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(header.Parameter))
if (string.Equals(header.Scheme, BearerScheme, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(header.Parameter))
{
resourceMetadataUrl = ParseWwwAuthenticateParameters(header.Parameter, "resource_metadata");
if (resourceMetadataUrl != null)

View file

@ -0,0 +1,17 @@
namespace ModelContextProtocol.Authentication;
/// <summary>
/// Allows the client to cache access tokens beyond the lifetime of the transport.
/// </summary>
public interface ITokenCache
{
/// <summary>
/// Cache the token. After a new access token is acquired, this method is invoked to store it.
/// </summary>
ValueTask StoreTokensAsync(TokenContainer tokens, CancellationToken cancellationToken);
/// <summary>
/// Get the cached token. This method is invoked for every request.
/// </summary>
ValueTask<TokenContainer?> GetTokensAsync(CancellationToken cancellationToken);
}

View file

@ -0,0 +1,27 @@
namespace ModelContextProtocol.Authentication;
/// <summary>
/// Caches the token in-memory within this instance.
/// </summary>
internal class InMemoryTokenCache : ITokenCache
{
private TokenContainer? _tokens;
/// <summary>
/// Cache the token.
/// </summary>
public ValueTask StoreTokensAsync(TokenContainer tokens, CancellationToken cancellationToken)
{
_tokens = tokens;
return default;
}
/// <summary>
/// Get the cached token.
/// </summary>
public ValueTask<TokenContainer?> GetTokensAsync(CancellationToken cancellationToken)
{
return new ValueTask<TokenContainer?>(_tokens);
}
}

View file

@ -1,57 +1,39 @@
using System.Text.Json.Serialization;
namespace ModelContextProtocol.Authentication;
/// <summary>
/// Represents a token response from the OAuth server.
/// Represents a cacheable combination of tokens ready to be used for authentication.
/// </summary>
internal sealed class TokenContainer
public sealed class TokenContainer
{
/// <summary>
/// Gets or sets the token type (typically "Bearer").
/// </summary>
public required string TokenType { get; set; }
/// <summary>
/// Gets or sets the access token.
/// </summary>
[JsonPropertyName("access_token")]
public string AccessToken { get; set; } = string.Empty;
public required string AccessToken { get; set; }
/// <summary>
/// Gets or sets the refresh token.
/// </summary>
[JsonPropertyName("refresh_token")]
public string? RefreshToken { get; set; }
/// <summary>
/// Gets or sets the number of seconds until the access token expires.
/// </summary>
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
/// <summary>
/// Gets or sets the extended expiration time in seconds.
/// </summary>
[JsonPropertyName("ext_expires_in")]
public int ExtExpiresIn { get; set; }
/// <summary>
/// Gets or sets the token type (typically "Bearer").
/// </summary>
[JsonPropertyName("token_type")]
public string TokenType { get; set; } = string.Empty;
public int? ExpiresIn { get; set; }
/// <summary>
/// Gets or sets the scope of the access token.
/// </summary>
[JsonPropertyName("scope")]
public string Scope { get; set; } = string.Empty;
public string? Scope { get; set; }
/// <summary>
/// Gets or sets the timestamp when the token was obtained.
/// </summary>
[JsonIgnore]
public DateTimeOffset ObtainedAt { get; set; }
public required DateTimeOffset ObtainedAt { get; set; }
/// <summary>
/// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.
/// </summary>
[JsonIgnore]
public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);
internal bool IsExpired => ExpiresIn is not null && DateTimeOffset.UtcNow >= ObtainedAt.AddSeconds(ExpiresIn.Value);
}

View file

@ -0,0 +1,39 @@
using System.Text.Json.Serialization;
namespace ModelContextProtocol.Authentication;
/// <summary>
/// Represents a token response from the OAuth server.
/// </summary>
internal sealed class TokenResponse
{
/// <summary>
/// Gets or sets the access token.
/// </summary>
[JsonPropertyName("access_token")]
public required string AccessToken { get; set; }
/// <summary>
/// Gets or sets the refresh token.
/// </summary>
[JsonPropertyName("refresh_token")]
public string? RefreshToken { get; set; }
/// <summary>
/// Gets or sets the number of seconds until the access token expires.
/// </summary>
[JsonPropertyName("expires_in")]
public int? ExpiresIn { get; set; }
/// <summary>
/// Gets or sets the token type (typically "Bearer").
/// </summary>
[JsonPropertyName("token_type")]
public required string TokenType { get; set; }
/// <summary>
/// Gets or sets the scope of the access token.
/// </summary>
[JsonPropertyName("scope")]
public string? Scope { get; set; }
}

View file

@ -158,7 +158,7 @@ public static partial class McpJsonUtilities
[JsonSerializable(typeof(ProtectedResourceMetadata))]
[JsonSerializable(typeof(AuthorizationServerMetadata))]
[JsonSerializable(typeof(TokenContainer))]
[JsonSerializable(typeof(TokenResponse))]
[JsonSerializable(typeof(DynamicClientRegistrationRequest))]
[JsonSerializable(typeof(DynamicClientRegistrationResponse))]

View file

@ -0,0 +1,280 @@
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
using System.Net;
using System.Net.Http.Json;
namespace ModelContextProtocol.AspNetCore.Tests.OAuth;
/// <summary>
/// Tests for MCP authentication when resource metadata is provided via events rather than static configuration.
/// </summary>
public class AuthEventTests : OAuthTestBase
{
public AuthEventTests(ITestOutputHelper outputHelper)
: base(outputHelper, configureMcpMetadata: false)
{
Builder.Services.Configure<McpAuthenticationOptions>(McpAuthenticationDefaults.AuthenticationScheme, options =>
{
// Note: ResourceMetadata is NOT set here - it will be provided via events
options.ResourceMetadata = null;
options.Events.OnResourceMetadataRequest = async context =>
{
// Dynamically provide the resource metadata
context.ResourceMetadata = new ProtectedResourceMetadata
{
Resource = new Uri(McpServerUrl),
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:tools"],
};
await Task.CompletedTask;
};
});
}
[Fact]
public async Task CanAuthenticate_WithResourceMetadataFromEvent()
{
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
);
await using var client = await McpClient.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken
);
}
[Fact]
public async Task CanAuthenticate_WithDynamicClientRegistration_FromEvent()
{
await using var app = await StartMcpServerAsync();
DynamicClientRegistrationResponse? dcrResponse = null;
await using var transport = new HttpClientTransport(
new()
{
Endpoint = new(McpServerUrl),
OAuth = new ClientOAuthOptions()
{
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
Scopes = ["mcp:tools"],
DynamicClientRegistration = new()
{
ClientName = "Test MCP Client",
ClientUri = new Uri("https://example.com"),
ResponseDelegate = (response, cancellationToken) =>
{
dcrResponse = response;
return Task.CompletedTask;
},
},
},
},
HttpClient,
LoggerFactory
);
await using var client = await McpClient.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken
);
Assert.NotNull(dcrResponse);
Assert.False(string.IsNullOrEmpty(dcrResponse.ClientId));
Assert.False(string.IsNullOrEmpty(dcrResponse.ClientSecret));
}
[Fact]
public async Task ResourceMetadataEndpoint_ReturnsCorrectMetadata_FromEvent()
{
await using var app = await StartMcpServerAsync();
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var metadata = await response.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);
}
[Fact]
public async Task ResourceMetadataEndpoint_CanModifyExistingMetadata_InEvent()
{
// Override the configuration to test modification of existing metadata
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
// Set initial metadata
options.ResourceMetadata = new ProtectedResourceMetadata
{
Resource = new Uri(McpServerUrl),
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:basic"],
};
// Override the event to modify the metadata
options.Events.OnResourceMetadataRequest = async context =>
{
// Start with the existing metadata and modify it
if (context.ResourceMetadata != null)
{
context.ResourceMetadata.ScopesSupported.Add("mcp:tools");
context.ResourceMetadata.ResourceName = "Dynamic Test Resource";
}
await Task.CompletedTask;
};
}
);
await using var app = await StartMcpServerAsync();
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var metadata = await response.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:basic", metadata.ScopesSupported);
Assert.Contains("mcp:tools", metadata.ScopesSupported);
Assert.Equal("Dynamic Test Resource", metadata.ResourceName);
}
[Fact]
public async Task ResourceMetadataEndpoint_ThrowsException_WhenNoMetadataProvided()
{
// Override the configuration to test the error case where no metadata is provided
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
// Don't set ResourceMetadata and provide an event that doesn't set it either
options.Events.OnResourceMetadataRequest = async context =>
{
// Intentionally don't set context.ResourceMetadata to test error handling
await Task.CompletedTask;
};
}
);
await using var app = await StartMcpServerAsync();
// Make a direct request to the resource metadata endpoint - this should fail
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// The request should fail with an internal server error due to the InvalidOperationException
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
[Fact]
public async Task ResourceMetadataEndpoint_HandlesResponse_WhenHandleResponseCalled()
{
// Override the configuration to test HandleResponse behavior
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.Events.OnResourceMetadataRequest = async context =>
{
// Call HandleResponse() to discontinue processing and return to client
context.HandleResponse();
await Task.CompletedTask;
};
}
);
await using var app = await StartMcpServerAsync();
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// The request should be handled by the event handler without returning metadata
// Since HandleResponse() was called, the handler should have taken responsibility
// for generating the response, which in this case means an empty response
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// The response should be empty since the event handler called HandleResponse()
// but didn't write any content to the response
var content = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Empty(content);
}
[Fact]
public async Task ResourceMetadataEndpoint_SkipsHandler_WhenSkipHandlerCalled()
{
// Override the configuration to test SkipHandler behavior
Builder.Services.Configure<McpAuthenticationOptions>(
McpAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.Events.OnResourceMetadataRequest = async context =>
{
// Call SkipHandler() to discontinue processing in the current handler
context.SkipHandler();
await Task.CompletedTask;
};
}
);
await using var app = await StartMcpServerAsync();
// Make a direct request to the resource metadata endpoint
using var response = await HttpClient.GetAsync(
"/.well-known/oauth-protected-resource",
TestContext.Current.CancellationToken
);
// When SkipHandler() is called, the authentication handler should skip processing
// and let other handlers in the pipeline handle the request. Since there are no
// other handlers configured for this endpoint, this should result in a 404
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}

View file

@ -0,0 +1,285 @@
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
using System.Net;
using System.Reflection;
using Xunit.Sdk;
namespace ModelContextProtocol.AspNetCore.Tests.OAuth;
public class AuthTests : OAuthTestBase
{
public AuthTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public async Task CanAuthenticate()
{
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);
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task CannotAuthenticate_WithoutOAuthConfiguration()
{
await using var app = await StartMcpServerAsync();
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
}, HttpClient, LoggerFactory);
var httpEx = await Assert.ThrowsAsync<HttpRequestException>(async () => await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(HttpStatusCode.Unauthorized, httpEx.StatusCode);
}
[Fact]
public async Task CannotAuthenticate_WithUnregisteredClient()
{
await using var app = await StartMcpServerAsync();
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "unregistered-demo-client",
ClientSecret = "demo-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
},
}, HttpClient, LoggerFactory);
// The EqualException is thrown by HandleAuthorizationUrlAsync when the /authorize request gets a 400
var equalEx = await Assert.ThrowsAsync<EqualException>(async () => await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task CanAuthenticate_WithDynamicClientRegistration()
{
await using var app = await StartMcpServerAsync();
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new ClientOAuthOptions()
{
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
Scopes = ["mcp:tools"],
DynamicClientRegistration = new()
{
ClientName = "Test MCP Client",
ClientUri = new Uri("https://example.com"),
},
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task CanAuthenticate_WithTokenRefresh()
{
await using var app = await StartMcpServerAsync();
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "test-refresh-client",
ClientSecret = "test-refresh-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,
},
}, HttpClient, LoggerFactory);
// The test-refresh-client should get an expired token first,
// then automatically refresh it to get a working token
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(TestOAuthServer.HasRefreshedToken);
}
[Fact]
public async Task CanAuthenticate_WithExtraParams()
{
await using var app = await StartMcpServerAsync();
Uri? lastAuthorizationUri = null;
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 = (uri, redirect, ct) =>
{
lastAuthorizationUri = uri;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
AdditionalAuthorizationParameters = new Dictionary<string, string>
{
["custom_param"] = "custom_value",
}
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(lastAuthorizationUri?.Query);
Assert.Contains("custom_param=custom_value", lastAuthorizationUri?.Query);
}
[Fact]
public async Task CannotOverrideExistingParameters_WithExtraParams()
{
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,
AdditionalAuthorizationParameters = new Dictionary<string, string>
{
["redirect_uri"] = "custom_value",
}
},
}, HttpClient, LoggerFactory);
await Assert.ThrowsAsync<ArgumentException>(() => McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public void CloneResourceMetadataClonesAllProperties()
{
var propertyNames = typeof(ProtectedResourceMetadata).GetProperties().Select(property => property.Name).ToList();
// Set metadata properties to non-default values to verify they're copied.
var metadata = new ProtectedResourceMetadata
{
Resource = new Uri("https://example.com/resource"),
AuthorizationServers = [new Uri("https://auth1.example.com"), new Uri("https://auth2.example.com")],
BearerMethodsSupported = ["header", "body", "query"],
ScopesSupported = ["read", "write", "admin"],
JwksUri = new Uri("https://example.com/.well-known/jwks.json"),
ResourceSigningAlgValuesSupported = ["RS256", "ES256"],
ResourceName = "Test Resource",
ResourceDocumentation = new Uri("https://docs.example.com"),
ResourcePolicyUri = new Uri("https://example.com/policy"),
ResourceTosUri = new Uri("https://example.com/terms"),
TlsClientCertificateBoundAccessTokens = true,
AuthorizationDetailsTypesSupported = ["payment_initiation", "account_information"],
DpopSigningAlgValuesSupported = ["RS256", "PS256"],
DpopBoundAccessTokensRequired = true
};
// Use reflection to call the internal CloneResourceMetadata method
var handlerType = typeof(McpAuthenticationHandler);
var cloneMethod = handlerType.GetMethod("CloneResourceMetadata", BindingFlags.Static | BindingFlags.NonPublic);
Assert.NotNull(cloneMethod);
var clonedMetadata = (ProtectedResourceMetadata?)cloneMethod.Invoke(null, [metadata]);
Assert.NotNull(clonedMetadata);
// Ensure the cloned metadata is not the same instance
Assert.NotSame(metadata, clonedMetadata);
// Verify Resource property
Assert.Equal(metadata.Resource, clonedMetadata.Resource);
Assert.True(propertyNames.Remove(nameof(metadata.Resource)));
// Verify AuthorizationServers list is cloned and contains the same values
Assert.NotSame(metadata.AuthorizationServers, clonedMetadata.AuthorizationServers);
Assert.Equal(metadata.AuthorizationServers, clonedMetadata.AuthorizationServers);
Assert.True(propertyNames.Remove(nameof(metadata.AuthorizationServers)));
// Verify BearerMethodsSupported list is cloned and contains the same values
Assert.NotSame(metadata.BearerMethodsSupported, clonedMetadata.BearerMethodsSupported);
Assert.Equal(metadata.BearerMethodsSupported, clonedMetadata.BearerMethodsSupported);
Assert.True(propertyNames.Remove(nameof(metadata.BearerMethodsSupported)));
// Verify ScopesSupported list is cloned and contains the same values
Assert.NotSame(metadata.ScopesSupported, clonedMetadata.ScopesSupported);
Assert.Equal(metadata.ScopesSupported, clonedMetadata.ScopesSupported);
Assert.True(propertyNames.Remove(nameof(metadata.ScopesSupported)));
// Verify JwksUri property
Assert.Equal(metadata.JwksUri, clonedMetadata.JwksUri);
Assert.True(propertyNames.Remove(nameof(metadata.JwksUri)));
// Verify ResourceSigningAlgValuesSupported list is cloned (nullable list)
Assert.NotSame(metadata.ResourceSigningAlgValuesSupported, clonedMetadata.ResourceSigningAlgValuesSupported);
Assert.Equal(metadata.ResourceSigningAlgValuesSupported, clonedMetadata.ResourceSigningAlgValuesSupported);
Assert.True(propertyNames.Remove(nameof(metadata.ResourceSigningAlgValuesSupported)));
// Verify ResourceName property
Assert.Equal(metadata.ResourceName, clonedMetadata.ResourceName);
Assert.True(propertyNames.Remove(nameof(metadata.ResourceName)));
// Verify ResourceDocumentation property
Assert.Equal(metadata.ResourceDocumentation, clonedMetadata.ResourceDocumentation);
Assert.True(propertyNames.Remove(nameof(metadata.ResourceDocumentation)));
// Verify ResourcePolicyUri property
Assert.Equal(metadata.ResourcePolicyUri, clonedMetadata.ResourcePolicyUri);
Assert.True(propertyNames.Remove(nameof(metadata.ResourcePolicyUri)));
// Verify ResourceTosUri property
Assert.Equal(metadata.ResourceTosUri, clonedMetadata.ResourceTosUri);
Assert.True(propertyNames.Remove(nameof(metadata.ResourceTosUri)));
// Verify TlsClientCertificateBoundAccessTokens property
Assert.Equal(metadata.TlsClientCertificateBoundAccessTokens, clonedMetadata.TlsClientCertificateBoundAccessTokens);
Assert.True(propertyNames.Remove(nameof(metadata.TlsClientCertificateBoundAccessTokens)));
// Verify AuthorizationDetailsTypesSupported list is cloned (nullable list)
Assert.NotSame(metadata.AuthorizationDetailsTypesSupported, clonedMetadata.AuthorizationDetailsTypesSupported);
Assert.Equal(metadata.AuthorizationDetailsTypesSupported, clonedMetadata.AuthorizationDetailsTypesSupported);
Assert.True(propertyNames.Remove(nameof(metadata.AuthorizationDetailsTypesSupported)));
// Verify DpopSigningAlgValuesSupported list is cloned (nullable list)
Assert.NotSame(metadata.DpopSigningAlgValuesSupported, clonedMetadata.DpopSigningAlgValuesSupported);
Assert.Equal(metadata.DpopSigningAlgValuesSupported, clonedMetadata.DpopSigningAlgValuesSupported);
Assert.True(propertyNames.Remove(nameof(metadata.DpopSigningAlgValuesSupported)));
// Verify DpopBoundAccessTokensRequired property
Assert.Equal(metadata.DpopBoundAccessTokensRequired, clonedMetadata.DpopBoundAccessTokensRequired);
Assert.True(propertyNames.Remove(nameof(metadata.DpopBoundAccessTokensRequired)));
// Ensure we've checked every property. When new properties get added, we'll have to update this test along with the CloneResourceMetadata implementation.
Assert.Empty(propertyNames);
}
}

View file

@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.AspNetCore.Tests.Utils;
using ModelContextProtocol.Authentication;
using System.Net;
using Xunit.Sdk;
namespace ModelContextProtocol.AspNetCore.Tests.OAuth;
public abstract class OAuthTestBase : KestrelInMemoryTest, IAsyncDisposable
{
protected const string McpServerUrl = "http://localhost:5000";
protected const string OAuthServerUrl = "https://localhost:7029";
protected readonly CancellationTokenSource TestCts = new();
protected readonly TestOAuthServer.Program TestOAuthServer;
private readonly Task _testOAuthRunTask;
protected OAuthTestBase(ITestOutputHelper outputHelper, bool configureMcpMetadata = true)
: base(outputHelper)
{
// Let the HandleAuthorizationUrlAsync take a look at the Location header
SocketsHttpHandler.AllowAutoRedirect = false;
// The dev cert may not be installed on the CI, but AddJwtBearer requires an HTTPS backchannel by default.
// The easiest workaround is to disable cert validation for testing purposes.
SocketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true;
TestOAuthServer = new TestOAuthServer.Program(XunitLoggerProvider, KestrelInMemoryTransport);
_testOAuthRunTask = TestOAuthServer.RunServerAsync(cancellationToken: TestCts.Token);
Builder.Services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Backchannel = HttpClient;
options.Authority = OAuthServerUrl;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = McpServerUrl,
ValidIssuer = OAuthServerUrl,
NameClaimType = "name",
RoleClaimType = "roles"
};
})
.AddMcp(options =>
{
if (configureMcpMetadata)
{
options.ResourceMetadata = new ProtectedResourceMetadata
{
Resource = new Uri(McpServerUrl),
AuthorizationServers = { new Uri(OAuthServerUrl) },
ScopesSupported = ["mcp:tools"]
};
}
});
Builder.Services.AddAuthorization();
Builder.Services.AddMcpServer().WithHttpTransport();
}
public async ValueTask DisposeAsync()
{
TestCts.Cancel();
try
{
await _testOAuthRunTask;
}
catch (OperationCanceledException)
{
}
finally
{
TestCts.Dispose();
}
}
protected async Task<WebApplication> StartMcpServerAsync()
{
var app = Builder.Build();
app.MapMcp().RequireAuthorization();
await app.StartAsync(TestContext.Current.CancellationToken);
return app;
}
protected async Task<string?> HandleAuthorizationUrlAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
{
using var redirectResponse = await HttpClient.GetAsync(authorizationUri, cancellationToken);
Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode);
var location = redirectResponse.Headers.Location;
if (location is not null && !string.IsNullOrEmpty(location.Query))
{
var queryParams = QueryHelpers.ParseQuery(location.Query);
return queryParams["code"];
}
return null;
}
}

View file

@ -0,0 +1,215 @@
using ModelContextProtocol.Authentication;
using ModelContextProtocol.Client;
namespace ModelContextProtocol.AspNetCore.Tests.OAuth;
public class TokenCacheTests : OAuthTestBase
{
public TokenCacheTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public async Task GetTokenAsync_CachedAccessTokenIsUsedForOutgoingRequests()
{
await using var app = await StartMcpServerAsync();
var tokenCache = new TestTokenCache();
bool authDelegateCalledInitially = false;
await using var setupTransport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "demo-client",
ClientSecret = "demo-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
{
authDelegateCalledInitially = true;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
TokenCache = tokenCache,
},
}, HttpClient, LoggerFactory);
await using (var setupClient = await McpClient.CreateAsync(setupTransport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken))
{
// Just connecting should trigger auth and storage.
}
Assert.True(authDelegateCalledInitially, "AuthorizationRedirectDelegate should be called to get initial token");
Assert.NotNull(tokenCache.LastStoredToken);
var authDelegateCalledAgain = false;
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 = (uri, redirect, ct) =>
{
authDelegateCalledAgain = true;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
TokenCache = tokenCache
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.False(authDelegateCalledAgain, "AuthorizationRedirectDelegate should not be called when token is valid");
}
[Fact]
public async Task StoreTokenAsync_NewlyAcquiredAccessTokenIsCached()
{
await using var app = await StartMcpServerAsync();
var tokenCache = new TestTokenCache();
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,
TokenCache = tokenCache
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(tokenCache.LastStoredToken);
Assert.False(string.IsNullOrEmpty(tokenCache.LastStoredToken.AccessToken));
}
[Fact]
public async Task GetTokenAsync_InvalidCachedTokenTriggersAuthDelegate()
{
await using var app = await StartMcpServerAsync();
var tokenCache = new TestTokenCache(CreateInvalidToken());
bool authDelegateCalled = false;
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 = (uri, redirect, ct) =>
{
authDelegateCalled = true;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
TokenCache = tokenCache,
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(authDelegateCalled, "AuthorizationRedirectDelegate should be called when cached token is invalid");
Assert.NotNull(tokenCache.LastStoredToken);
Assert.NotEqual("invalid-token", tokenCache.LastStoredToken.AccessToken);
}
[Fact]
public async Task GetTokenAsync_InvalidAccessTokenTriggersRefresh()
{
await using var app = await StartMcpServerAsync();
var tokenCache = new TestTokenCache();
bool authDelegateCalledInitially = false;
await using var setupTransport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
{
ClientId = "demo-client",
ClientSecret = "demo-secret",
RedirectUri = new Uri("http://localhost:1179/callback"),
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
{
authDelegateCalledInitially = true;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
TokenCache = tokenCache,
},
}, HttpClient, LoggerFactory);
await using (var setupClient = await McpClient.CreateAsync(setupTransport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken))
{
// Just connecting should trigger auth and storage.
}
Assert.True(authDelegateCalledInitially, "AuthorizationRedirectDelegate should be called to get initial token");
Assert.False(TestOAuthServer.HasRefreshedToken, "Token should not have been refreshed yet");
Assert.NotNull(tokenCache.LastStoredToken);
// Invalidate the access token but keep the refresh token valid (if any)
tokenCache.LastStoredToken.AccessToken = "invalid-token";
var authDelegateCalledAgain = false;
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 = (uri, redirect, ct) =>
{
authDelegateCalledAgain = true;
return HandleAuthorizationUrlAsync(uri, redirect, ct);
},
TokenCache = tokenCache
},
}, HttpClient, LoggerFactory);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.False(authDelegateCalledAgain, "AuthorizationRedirectDelegate should not be called when refresh token is valid");
Assert.True(TestOAuthServer.HasRefreshedToken, "Token should have been refreshed");
Assert.NotEqual("invalid-token", tokenCache.LastStoredToken.AccessToken);
}
private TokenContainer CreateInvalidToken()
{
return new TokenContainer
{
TokenType = "Bearer",
AccessToken = "invalid-token",
ObtainedAt = DateTimeOffset.UtcNow,
};
}
private class TestTokenCache(TokenContainer? initialToken = null) : ITokenCache
{
public TokenContainer? LastStoredToken { get; private set; } = initialToken;
public ValueTask<TokenContainer?> GetTokensAsync(CancellationToken cancellationToken)
{
return new ValueTask<TokenContainer?>(LastStoredToken);
}
public ValueTask StoreTokensAsync(TokenContainer tokens, CancellationToken cancellationToken)
{
LastStoredToken = tokens;
return ValueTask.CompletedTask;
}
}
}

View file

@ -42,7 +42,7 @@ public sealed class Program
// Track if we've already issued an already-expired token for the CanAuthenticate_WithTokenRefresh test which uses the test-refresh-client registration.
public bool HasIssuedExpiredToken { get; set; }
public bool HasIssuedRefreshToken { get; set; }
public bool HasRefreshedToken { get; set; }
/// <summary>
/// Entry point for the application.
@ -368,7 +368,7 @@ public sealed class Program
_tokens.TryRemove(refresh_token, out _);
}
HasIssuedRefreshToken = true;
HasRefreshedToken = true;
return Results.Ok(response);
}
else