-
Notifications
You must be signed in to change notification settings - Fork 729
Expand file tree
/
Copy pathMcpAuthenticationHandler.cs
More file actions
212 lines (175 loc) · 7.92 KB
/
Copy pathMcpAuthenticationHandler.cs
File metadata and controls
212 lines (175 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using ModelContextProtocol.Authentication;
using System.Text.Encodings.Web;
namespace ModelContextProtocol.AspNetCore.Authentication;
/// <summary>
/// Represents an authentication handler for MCP protocol that adds resource metadata to challenge responses
/// and handles resource metadata endpoint requests.
/// </summary>
public partial class McpAuthenticationHandler : AuthenticationHandler<McpAuthenticationOptions>, IAuthenticationRequestHandler
{
private const string DefaultResourceMetadataPath = "/.well-known/oauth-protected-resource";
private static readonly PathString DefaultResourceMetadataPrefix = new(DefaultResourceMetadataPath);
/// <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 Task<bool> HandleRequestAsync()
{
if (Options.ResourceMetadataUri is Uri configuredUri)
{
return HandleConfiguredResourceMetadataRequestAsync(configuredUri);
}
return HandleDefaultResourceMetadataRequestAsync();
}
private async Task<bool> HandleConfiguredResourceMetadataRequestAsync(Uri resourceMetadataUri)
{
if (!IsConfiguredEndpointRequest(resourceMetadataUri))
{
return false;
}
return await HandleResourceMetadataRequestAsync();
}
private async Task<bool> HandleDefaultResourceMetadataRequestAsync()
{
if (!Request.Path.StartsWithSegments(DefaultResourceMetadataPrefix, out var resourceSuffix))
{
return false;
}
// Build the derived resource string directly without trailing slash
var scheme = Request.Scheme;
var host = Request.Host.Host;
var port = Request.Host.Port;
var path = $"{Request.PathBase}{resourceSuffix}".TrimEnd('/');
string derivedResource;
if (port.HasValue && !IsDefaultPort(scheme, port.Value))
{
derivedResource = $"{scheme}://{host}:{port.Value}{path}";
}
else
{
derivedResource = $"{scheme}://{host}{path}";
}
return await HandleResourceMetadataRequestAsync(derivedResource);
}
private static bool IsDefaultPort(string scheme, int port)
{
return (scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && port == 80) ||
(scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && port == 443);
}
/// <summary>
/// Gets the absolute URI for the resource metadata endpoint.
/// </summary>
private string GetAbsoluteResourceMetadataUri()
{
if (Options.ResourceMetadataUri is Uri resourceMetadataUri)
{
if (resourceMetadataUri.IsAbsoluteUri)
{
return resourceMetadataUri.ToString();
}
var separator = resourceMetadataUri.OriginalString.StartsWith('/') ? "" : "/";
return $"{Request.Scheme}://{Request.Host.ToUriComponent()}{Request.PathBase}{separator}{resourceMetadataUri.OriginalString}";
}
return $"{Request.Scheme}://{Request.Host.ToUriComponent()}{Request.PathBase}{DefaultResourceMetadataPath}{Request.Path}";
}
private bool IsConfiguredEndpointRequest(Uri resourceMetadataUri)
{
var expectedPath = GetConfiguredResourceMetadataPath(resourceMetadataUri);
if (!string.Equals(Request.Path.Value, expectedPath, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!resourceMetadataUri.IsAbsoluteUri)
{
return true;
}
if (!string.Equals(Request.Host.Host, resourceMetadataUri.Host, StringComparison.OrdinalIgnoreCase))
{
LogResourceMetadataHostMismatch(Logger, resourceMetadataUri.Host);
return false;
}
if (!string.Equals(Request.Scheme, resourceMetadataUri.Scheme, StringComparison.OrdinalIgnoreCase))
{
LogResourceMetadataSchemeMismatch(Logger, resourceMetadataUri.Scheme);
return false;
}
return true;
}
private static string GetConfiguredResourceMetadataPath(Uri resourceMetadataUri)
{
if (resourceMetadataUri.IsAbsoluteUri)
{
return resourceMetadataUri.AbsolutePath;
}
var path = resourceMetadataUri.OriginalString;
return path.StartsWith('/') ? path : $"/{path}";
}
private async Task<bool> HandleResourceMetadataRequestAsync(string? derivedResource = null)
{
var resourceMetadata = Options.ResourceMetadata?.Clone(derivedResource);
if (Options.Events.OnResourceMetadataRequest is not null)
{
var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)
{
ResourceMetadata = resourceMetadata,
};
await Options.Events.OnResourceMetadataRequest(context);
if (context.Result is not null)
{
if (context.Result.Handled)
{
return true;
}
else if (context.Result.Skipped)
{
return false;
}
else if (context.Result.Failure is not null)
{
throw new AuthenticationFailureException("An error occurred from the OnResourceMetadataRequest event.", context.Result.Failure);
}
}
resourceMetadata = context.ResourceMetadata;
}
if (resourceMetadata is null)
{
throw new InvalidOperationException("ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.");
}
resourceMetadata.Resource ??= derivedResource;
if (resourceMetadata.Resource is null)
{
throw new InvalidOperationException("ResourceMetadata.Resource could not be determined. Please set McpAuthenticationOptions.ResourceMetadata.Resource or avoid setting a custom McpAuthenticationOptions.ResourceMetadataUri.");
}
await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);
return true;
}
/// <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();
// Add the WWW-Authenticate header with Bearer scheme and resource metadata
string headerValue = $"Bearer resource_metadata=\"{rawPrmDocumentUri}\"";
Response.Headers.Append(HeaderNames.WWWAuthenticate, headerValue);
return base.HandleChallengeAsync(properties);
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Resource metadata request host did not match configured host '{ConfiguredHost}'.")]
private static partial void LogResourceMetadataHostMismatch(ILogger logger, string configuredHost);
[LoggerMessage(Level = LogLevel.Warning, Message = "Resource metadata request scheme did not match configured scheme '{ConfiguredScheme}'.")]
private static partial void LogResourceMetadataSchemeMismatch(ILogger logger, string configuredScheme);
}