Repository navigation
Expand file tree
/
Copy pathIdentityAssertionGrantProvider.cs
More file actions
331 lines (290 loc) · 15.3 KB
/
Copy pathIdentityAssertionGrantProvider.cs
File metadata and controls
331 lines (290 loc) · 15.3 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ModelContextProtocol.Authentication;
/// <summary>
/// Provides Cross-Application Access authorization as a standalone, non-interactive provider
/// that can be used alongside the MCP client's OAuth infrastructure.
/// </summary>
/// <remarks>
/// <para>
/// This provider implements the full Identity Assertion Authorization Grant flow as specified at
/// <see href="https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/draft/enterprise-managed-authorization.mdx"/>:
/// </para>
/// <list type="number">
/// <item><description>
/// The <see cref="IdentityAssertionGrantProviderOptions.IdTokenCallback"/> is called to obtain an OIDC ID token.
/// It receives a <see cref="IdentityAssertionGrantContext"/> with the discovered resource and authorization
/// server URLs.
/// </description></item>
/// <item><description>
/// The provider performs the RFC 8693 token exchange at the enterprise Identity Provider
/// (using the configured <c>IdpTokenEndpoint</c> or discovered from <c>IdpUrl</c>),
/// exchanging the ID token for a JWT Authorization Grant (JAG).
/// </description></item>
/// <item><description>
/// The JAG is then exchanged for an access token at the MCP Server's authorization server
/// via the RFC 7523 JWT Bearer grant.
/// </description></item>
/// </list>
/// <para>
/// Concurrency: a single provider instance may be shared across concurrent requests. Token
/// acquisition is coalesced through an internal lock, so if several callers observe an expired or
/// absent token at the same time, only one runs the exchange flow and the others await and reuse
/// its result. The cached token is refreshed at most once per expiry.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// var provider = new IdentityAssertionGrantProvider(
/// new IdentityAssertionGrantProviderOptions
/// {
/// ClientId = "mcp-client-id",
/// IdpTokenEndpoint = "https://company.okta.com/oauth2/token",
/// IdpClientId = "idp-client-id",
/// IdTokenCallback = (context, ct) =>
/// mySsoClient.GetIdTokenAsync(ct)
/// },
/// httpClient: myHttpClient);
///
/// var tokens = await provider.GetAccessTokenAsync(
/// resourceUrl: new Uri("https://mcp-server.example.com"),
/// authorizationServerUrl: new Uri("https://auth.example.com"),
/// cancellationToken: ct);
/// </code>
/// </example>
public sealed class IdentityAssertionGrantProvider
{
private readonly IdentityAssertionGrantProviderOptions _options;
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
private TokenContainer? _cachedTokens;
// Coalesces concurrent token acquisition so that when multiple in-flight requests observe an
// expired/absent token at the same time, only the first runs the exchange flow while the others
// await its result. Also serializes writes to _cachedTokens and _resolvedIdpTokenEndpoint.
//
// Intentionally not disposed: this instance is only ever used via WaitAsync/Wait/Release (never
// its AvailableWaitHandle), so SemaphoreSlim allocates no unmanaged resource and there is nothing
// to dispose. Do not access AvailableWaitHandle, or this field will need deterministic disposal.
private readonly SemaphoreSlim _tokenAcquisitionLock = new(1, 1);
/// <summary>
/// Initializes a new instance of the <see cref="IdentityAssertionGrantProvider"/> class.
/// </summary>
/// <param name="options">Configuration for the Cross-Application Access provider.</param>
/// <param name="httpClient">
/// The HTTP client to use for token exchange requests. The caller is responsible for the lifetime of this instance.
/// </param>
/// <param name="loggerFactory">Optional logger factory.</param>
/// <exception cref="ArgumentNullException"><paramref name="options"/> or <paramref name="httpClient"/> is null.</exception>
/// <exception cref="ArgumentException">Required option values are missing.</exception>
public IdentityAssertionGrantProvider(
IdentityAssertionGrantProviderOptions options,
HttpClient httpClient,
ILoggerFactory? loggerFactory = null)
{
Throw.IfNull(options);
Throw.IfNull(httpClient);
Throw.IfNullOrWhiteSpace(options.ClientId);
Throw.IfNullOrWhiteSpace(options.IdpClientId);
if (string.IsNullOrEmpty(options.IdpUrl) && string.IsNullOrEmpty(options.IdpTokenEndpoint))
{
throw new ArgumentException("Either IdpUrl or IdpTokenEndpoint is required.", $"{nameof(options)}.{nameof(options.IdpUrl)}");
}
if (options.IdTokenCallback is null)
{
throw new ArgumentNullException($"{nameof(options)}.{nameof(options.IdTokenCallback)}");
}
if (options.TokenEndpointAuthMethod is not null &&
options.TokenEndpointAuthMethod is not ("client_secret_basic" or "client_secret_post" or "none"))
{
throw new ArgumentException(
$"{nameof(options.TokenEndpointAuthMethod)} must be 'client_secret_basic', 'client_secret_post', or 'none'.",
$"{nameof(options)}.{nameof(options.TokenEndpointAuthMethod)}");
}
if (options.TokenEndpointAuthMethod is "client_secret_basic" or "client_secret_post" &&
string.IsNullOrEmpty(options.ClientSecret))
{
throw new ArgumentException(
$"{nameof(options.ClientSecret)} is required when {nameof(options.TokenEndpointAuthMethod)} is '{options.TokenEndpointAuthMethod}'.",
$"{nameof(options)}.{nameof(options.ClientSecret)}");
}
_options = options;
_httpClient = httpClient;
_logger = (ILogger?)loggerFactory?.CreateLogger<IdentityAssertionGrantProvider>() ?? NullLogger.Instance;
}
/// <summary>
/// Performs the full Cross-Application Access flow to obtain an access token for the given MCP resource.
/// </summary>
/// <param name="resourceUrl">
/// The canonical MCP resource identifier. Its <see cref="Uri.OriginalString"/> is sent unchanged as the resource parameter.
/// </param>
/// <param name="authorizationServerUrl">The MCP authorization server URL.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
/// <returns>A <see cref="TokenContainer"/> containing the access token.</returns>
/// <exception cref="IdentityAssertionGrantException">Thrown when any step of the flow fails.</exception>
public async Task<TokenContainer> GetAccessTokenAsync(
Uri resourceUrl,
Uri authorizationServerUrl,
CancellationToken cancellationToken = default)
{
// Return cached token if still valid. Read the field once into a local so a concurrent
// InvalidateCache (which nulls _cachedTokens) cannot turn this lock-free check into a null
// dereference or a null return between the null check and the return.
var cachedBeforeLock = _cachedTokens;
if (cachedBeforeLock is not null && !cachedBeforeLock.IsExpired)
{
return cachedBeforeLock;
}
// Serialize the exchange so concurrent callers that all saw the expired/absent token don't
// each run the full multi-step flow. Waiters re-check the cache after acquiring the lock and
// reuse the token produced by whoever ran the exchange first.
using var _ = await _tokenAcquisitionLock.LockAsync(cancellationToken).ConfigureAwait(false);
if (_cachedTokens is not null && !_cachedTokens.IsExpired)
{
return _cachedTokens;
}
return await AcquireAccessTokenAsync(resourceUrl, authorizationServerUrl, cancellationToken).ConfigureAwait(false);
}
private async Task<TokenContainer> AcquireAccessTokenAsync(
Uri resourceUrl,
Uri authorizationServerUrl,
CancellationToken cancellationToken)
{
_logger.LogDebug("Starting Cross-Application Access flow for resource {ResourceUrl}", resourceUrl);
// Step 1: Discover MCP authorization server metadata to find the token endpoint
var mcpAuthMetadata = await IdentityAssertionGrant.DiscoverAuthServerMetadataAsync(
authorizationServerUrl, _httpClient, cancellationToken).ConfigureAwait(false);
// The issuer becomes the JAG audience below, so validate it first (RFC 8414 Section 3.3): it MUST be
// identical to the issuer identifier used for discovery. Like ClientOAuthProvider, compare the exact
// strings without normalizing case, trailing slashes or percent-encoding.
if (mcpAuthMetadata.Issuer is not null &&
!string.Equals(mcpAuthMetadata.Issuer.OriginalString, authorizationServerUrl.OriginalString, StringComparison.Ordinal))
{
throw new IdentityAssertionGrantException(
$"Authorization server metadata issuer '{mcpAuthMetadata.Issuer.OriginalString}' does not match the expected issuer '{authorizationServerUrl.OriginalString}' (RFC 8414 Section 3.3).");
}
var mcpTokenEndpoint = mcpAuthMetadata.TokenEndpoint?.ToString()
?? throw new IdentityAssertionGrantException(
$"MCP authorization server metadata at {authorizationServerUrl} missing token_endpoint.");
// Step 2: Call the ID token callback to get the caller's OIDC ID token
var context = new IdentityAssertionGrantContext
{
ResourceUrl = resourceUrl,
AuthorizationServerUrl = authorizationServerUrl,
};
_logger.LogDebug("Requesting ID token via callback");
var idToken = await _options.IdTokenCallback(context, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(idToken))
{
throw new IdentityAssertionGrantException("ID token callback returned a null or empty token.");
}
// Step 3: RFC 8693 token exchange — ID token → JWT Authorization Grant (JAG) at the enterprise IdP
_logger.LogDebug("Performing RFC 8693 token exchange at IdP");
var idpTokenEndpoint = await ResolveIdpTokenEndpointAsync(cancellationToken).ConfigureAwait(false);
var jag = await IdentityAssertionGrant.RequestJwtAuthorizationGrantAsync(
new RequestJwtAuthGrantOptions
{
TokenEndpoint = idpTokenEndpoint,
// The JAG audience is the MCP authorization server's issuer identifier (RFC 8414), not the
// caller-supplied URL, which can differ from it (e.g. Uri.ToString() appends a trailing slash).
// OriginalString preserves the advertised issuer exactly as published.
Audience = mcpAuthMetadata.Issuer?.OriginalString ?? authorizationServerUrl.ToString(),
Resource = resourceUrl.OriginalString,
IdToken = idToken,
ClientId = _options.IdpClientId,
ClientSecret = _options.IdpClientSecret,
Scope = _options.IdpScope,
}, _httpClient, cancellationToken).ConfigureAwait(false);
// Step 4: RFC 7523 JWT bearer grant — JAG → access token at the MCP authorization server
_logger.LogDebug("Exchanging JAG for access token at {McpTokenEndpoint}", mcpTokenEndpoint);
var tokens = await IdentityAssertionGrant.ExchangeJwtBearerGrantAsync(
new ExchangeJwtBearerGrantOptions
{
TokenEndpoint = mcpTokenEndpoint,
Assertion = jag,
ClientId = _options.ClientId,
ClientSecret = _options.ClientSecret,
TokenEndpointAuthMethod = SelectTokenEndpointAuthMethod(mcpAuthMetadata),
Scope = _options.Scope,
}, _httpClient, cancellationToken).ConfigureAwait(false);
_cachedTokens = tokens;
_logger.LogDebug("Cross-Application Access flow completed successfully");
return tokens;
}
private string SelectTokenEndpointAuthMethod(AuthorizationServerMetadata metadata)
{
var supportedMethods = metadata.TokenEndpointAuthMethodsSupported;
if (_options.TokenEndpointAuthMethod is { } configuredMethod)
{
if (supportedMethods is { Count: > 0 } &&
!supportedMethods.Contains(configuredMethod, StringComparer.Ordinal))
{
throw new IdentityAssertionGrantException(
$"The configured token endpoint authentication method '{configuredMethod}' is not advertised by the MCP authorization server.");
}
return configuredMethod;
}
if (string.IsNullOrEmpty(_options.ClientSecret))
{
if (supportedMethods is null or { Count: 0 } ||
supportedMethods.Contains("none", StringComparer.Ordinal))
{
return "none";
}
throw new IdentityAssertionGrantException(
"The MCP authorization server does not advertise a token endpoint authentication method usable without a client secret.");
}
// Preserve the provider's existing client_secret_post behavior when it is available.
// RFC 8414 defines this metadata as a list of supported methods, not a preference order.
if (supportedMethods is null or { Count: 0 } ||
supportedMethods.Contains("client_secret_post", StringComparer.Ordinal))
{
return "client_secret_post";
}
if (supportedMethods.Contains("client_secret_basic", StringComparer.Ordinal))
{
return "client_secret_basic";
}
throw new IdentityAssertionGrantException(
"The MCP authorization server does not advertise a supported token endpoint authentication method.");
}
/// <summary>
/// Clears any cached tokens, forcing a fresh token exchange on the next call to <see cref="GetAccessTokenAsync"/>.
/// </summary>
/// <remarks>
/// This blocks until any token acquisition that is currently in progress completes, so that the
/// invalidation is not silently overwritten by a concurrent exchange storing a freshly obtained token.
/// </remarks>
public void InvalidateCache()
{
_tokenAcquisitionLock.Wait();
try
{
_cachedTokens = null;
}
finally
{
_tokenAcquisitionLock.Release();
}
}
private string? _resolvedIdpTokenEndpoint;
private async Task<string> ResolveIdpTokenEndpointAsync(CancellationToken cancellationToken)
{
if (_resolvedIdpTokenEndpoint is not null)
{
return _resolvedIdpTokenEndpoint;
}
if (!string.IsNullOrEmpty(_options.IdpTokenEndpoint))
{
_resolvedIdpTokenEndpoint = _options.IdpTokenEndpoint!;
return _resolvedIdpTokenEndpoint;
}
// Discover from IdpUrl
var idpMetadata = await IdentityAssertionGrant.DiscoverAuthServerMetadataAsync(
new Uri(_options.IdpUrl!), _httpClient, cancellationToken).ConfigureAwait(false);
var resolved = idpMetadata.TokenEndpoint?.ToString()
?? throw new IdentityAssertionGrantException(
$"IdP metadata discovery for {_options.IdpUrl} did not return a token_endpoint.");
_resolvedIdpTokenEndpoint = resolved;
return resolved;
}
}