|
| 1 | +using System.Net.Http.Headers; |
| 2 | +using System.Text.Json; |
| 3 | + |
| 4 | +namespace ModelContextProtocol.Authentication; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Provides internal utilities for the Cross-Application Access authorization flow. |
| 8 | +/// </summary> |
| 9 | +/// <remarks> |
| 10 | +/// Implements the Enterprise Managed Authorization flow as specified at |
| 11 | +/// <see href="https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/draft/enterprise-managed-authorization.mdx"/>. |
| 12 | +/// </remarks> |
| 13 | +internal static class IdentityAssertionGrant |
| 14 | +{ |
| 15 | + #region Constants |
| 16 | + |
| 17 | + /// <summary>Grant type URN for RFC 8693 token exchange.</summary> |
| 18 | + public const string GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"; |
| 19 | + |
| 20 | + /// <summary>Grant type URN for RFC 7523 JWT Bearer authorization grant.</summary> |
| 21 | + public const string GrantTypeJwtBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer"; |
| 22 | + |
| 23 | + /// <summary>Token type URN for OpenID Connect ID Tokens (RFC 8693).</summary> |
| 24 | + public const string TokenTypeIdToken = "urn:ietf:params:oauth:token-type:id_token"; |
| 25 | + |
| 26 | + /// <summary>Token type URN for SAML 2.0 assertions (RFC 8693).</summary> |
| 27 | + public const string TokenTypeSaml2 = "urn:ietf:params:oauth:token-type:saml2"; |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// Token type URN for Identity Assertion JWT Authorization Grants. |
| 31 | + /// As specified at |
| 32 | + /// <see href="https://github.com/modelcontextprotocol/ext-auth/blob/main/specification/draft/enterprise-managed-authorization.mdx"/>. |
| 33 | + /// </summary> |
| 34 | + public const string TokenTypeIdJag = "urn:ietf:params:oauth:token-type:id-jag"; |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// The expected value for <c>token_type</c> in a JAG token exchange response per RFC 8693 §2.2.1. |
| 38 | + /// The issued token is not an OAuth access token, so its type is "N_A". |
| 39 | + /// </summary> |
| 40 | + public const string TokenTypeNotApplicable = "N_A"; |
| 41 | + |
| 42 | + #endregion |
| 43 | + |
| 44 | + #region Token Exchange (RFC 8693) |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Requests a JWT Authorization Grant (JAG) from an Identity Provider via RFC 8693 Token Exchange. |
| 48 | + /// Returns the JAG string to be used as a JWT Bearer assertion (RFC 7523) against the MCP authorization server. |
| 49 | + /// </summary> |
| 50 | + public static async Task<string> RequestJwtAuthorizationGrantAsync( |
| 51 | + RequestJwtAuthGrantOptions options, |
| 52 | + HttpClient httpClient, |
| 53 | + CancellationToken cancellationToken = default) |
| 54 | + { |
| 55 | + Throw.IfNull(options); |
| 56 | + Throw.IfNullOrWhiteSpace(options.TokenEndpoint); |
| 57 | + Throw.IfNullOrWhiteSpace(options.Audience); |
| 58 | + Throw.IfNullOrWhiteSpace(options.Resource); |
| 59 | + Throw.IfNullOrWhiteSpace(options.IdToken); |
| 60 | + Throw.IfNullOrWhiteSpace(options.ClientId); |
| 61 | + |
| 62 | + var formData = new Dictionary<string, string> |
| 63 | + { |
| 64 | + ["grant_type"] = GrantTypeTokenExchange, |
| 65 | + ["requested_token_type"] = TokenTypeIdJag, |
| 66 | + ["subject_token"] = options.IdToken, |
| 67 | + ["subject_token_type"] = TokenTypeIdToken, |
| 68 | + ["audience"] = options.Audience, |
| 69 | + ["resource"] = options.Resource, |
| 70 | + ["client_id"] = options.ClientId, |
| 71 | + }; |
| 72 | + |
| 73 | + if (!string.IsNullOrEmpty(options.ClientSecret)) |
| 74 | + { |
| 75 | + formData["client_secret"] = options.ClientSecret!; |
| 76 | + } |
| 77 | + |
| 78 | + if (!string.IsNullOrEmpty(options.Scope)) |
| 79 | + { |
| 80 | + formData["scope"] = options.Scope!; |
| 81 | + } |
| 82 | + |
| 83 | + using var requestContent = new FormUrlEncodedContent(formData); |
| 84 | + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, options.TokenEndpoint) |
| 85 | + { |
| 86 | + Content = requestContent |
| 87 | + }; |
| 88 | + |
| 89 | + httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 90 | + |
| 91 | + using var httpResponse = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); |
| 92 | + var responseBody = await httpResponse.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| 93 | + |
| 94 | + if (!httpResponse.IsSuccessStatusCode) |
| 95 | + { |
| 96 | + OAuthErrorResponse? errorResponse = null; |
| 97 | + try |
| 98 | + { |
| 99 | + errorResponse = JsonSerializer.Deserialize(responseBody, McpJsonUtilities.JsonContext.Default.OAuthErrorResponse); |
| 100 | + } |
| 101 | + catch |
| 102 | + { |
| 103 | + // Could not parse error response |
| 104 | + } |
| 105 | + |
| 106 | + throw new IdentityAssertionGrantException( |
| 107 | + $"Token exchange failed with status {(int)httpResponse.StatusCode}.", |
| 108 | + errorResponse?.Error, |
| 109 | + errorResponse?.ErrorDescription, |
| 110 | + errorResponse?.ErrorUri); |
| 111 | + } |
| 112 | + |
| 113 | + var response = JsonSerializer.Deserialize(responseBody, McpJsonUtilities.JsonContext.Default.JagTokenExchangeResponse); |
| 114 | + |
| 115 | + if (response is null) |
| 116 | + { |
| 117 | + var ex = new IdentityAssertionGrantException("Failed to parse token exchange response."); |
| 118 | + ex.Data["ResponseBody"] = responseBody; |
| 119 | + throw ex; |
| 120 | + } |
| 121 | + |
| 122 | + if (string.IsNullOrEmpty(response.AccessToken)) |
| 123 | + { |
| 124 | + throw new IdentityAssertionGrantException("Token exchange response missing required field: access_token"); |
| 125 | + } |
| 126 | + |
| 127 | + if (!string.Equals(response.IssuedTokenType, TokenTypeIdJag, StringComparison.Ordinal)) |
| 128 | + { |
| 129 | + throw new IdentityAssertionGrantException( |
| 130 | + $"Token exchange response issued_token_type must be '{TokenTypeIdJag}', got '{response.IssuedTokenType}'."); |
| 131 | + } |
| 132 | + |
| 133 | + if (!string.Equals(response.TokenType, TokenTypeNotApplicable, StringComparison.Ordinal)) |
| 134 | + { |
| 135 | + throw new IdentityAssertionGrantException( |
| 136 | + $"Token exchange response token_type must be '{TokenTypeNotApplicable}' per RFC 8693 §2.2.1, got '{response.TokenType}'."); |
| 137 | + } |
| 138 | + |
| 139 | + return response.AccessToken; |
| 140 | + } |
| 141 | + |
| 142 | + #endregion |
| 143 | + |
| 144 | + #region JWT Bearer Grant (RFC 7523) |
| 145 | + |
| 146 | + /// <summary> |
| 147 | + /// Exchanges a JWT Authorization Grant (JAG) for an access token at an MCP Server's authorization server |
| 148 | + /// using the JWT Bearer grant (RFC 7523). |
| 149 | + /// </summary> |
| 150 | + public static async Task<TokenContainer> ExchangeJwtBearerGrantAsync( |
| 151 | + ExchangeJwtBearerGrantOptions options, |
| 152 | + HttpClient httpClient, |
| 153 | + CancellationToken cancellationToken = default) |
| 154 | + { |
| 155 | + Throw.IfNull(options); |
| 156 | + Throw.IfNullOrWhiteSpace(options.TokenEndpoint); |
| 157 | + Throw.IfNullOrWhiteSpace(options.Assertion); |
| 158 | + Throw.IfNullOrWhiteSpace(options.ClientId); |
| 159 | + |
| 160 | + var formData = new Dictionary<string, string> |
| 161 | + { |
| 162 | + ["grant_type"] = GrantTypeJwtBearer, |
| 163 | + ["assertion"] = options.Assertion, |
| 164 | + ["client_id"] = options.ClientId, |
| 165 | + }; |
| 166 | + |
| 167 | + if (!string.IsNullOrEmpty(options.ClientSecret)) |
| 168 | + { |
| 169 | + formData["client_secret"] = options.ClientSecret!; |
| 170 | + } |
| 171 | + |
| 172 | + if (!string.IsNullOrEmpty(options.Scope)) |
| 173 | + { |
| 174 | + formData["scope"] = options.Scope!; |
| 175 | + } |
| 176 | + |
| 177 | + using var requestContent = new FormUrlEncodedContent(formData); |
| 178 | + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, options.TokenEndpoint) |
| 179 | + { |
| 180 | + Content = requestContent |
| 181 | + }; |
| 182 | + |
| 183 | + httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 184 | + |
| 185 | + using var httpResponse = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); |
| 186 | + var responseBody = await httpResponse.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| 187 | + |
| 188 | + if (!httpResponse.IsSuccessStatusCode) |
| 189 | + { |
| 190 | + OAuthErrorResponse? errorResponse = null; |
| 191 | + try |
| 192 | + { |
| 193 | + errorResponse = JsonSerializer.Deserialize(responseBody, McpJsonUtilities.JsonContext.Default.OAuthErrorResponse); |
| 194 | + } |
| 195 | + catch |
| 196 | + { |
| 197 | + // Could not parse error response |
| 198 | + } |
| 199 | + |
| 200 | + throw new IdentityAssertionGrantException( |
| 201 | + $"JWT bearer grant failed with status {(int)httpResponse.StatusCode}.", |
| 202 | + errorResponse?.Error, |
| 203 | + errorResponse?.ErrorDescription, |
| 204 | + errorResponse?.ErrorUri); |
| 205 | + } |
| 206 | + |
| 207 | + var response = JsonSerializer.Deserialize(responseBody, McpJsonUtilities.JsonContext.Default.JwtBearerAccessTokenResponse); |
| 208 | + |
| 209 | + if (response is null) |
| 210 | + { |
| 211 | + var ex = new IdentityAssertionGrantException("Failed to parse JWT bearer grant response."); |
| 212 | + ex.Data["ResponseBody"] = responseBody; |
| 213 | + throw ex; |
| 214 | + } |
| 215 | + |
| 216 | + if (string.IsNullOrEmpty(response.AccessToken)) |
| 217 | + { |
| 218 | + throw new IdentityAssertionGrantException("JWT bearer grant response missing required field: access_token"); |
| 219 | + } |
| 220 | + |
| 221 | + if (string.IsNullOrEmpty(response.TokenType)) |
| 222 | + { |
| 223 | + throw new IdentityAssertionGrantException("JWT bearer grant response missing required field: token_type"); |
| 224 | + } |
| 225 | + |
| 226 | + if (!string.Equals(response.TokenType, "bearer", StringComparison.OrdinalIgnoreCase)) |
| 227 | + { |
| 228 | + throw new IdentityAssertionGrantException( |
| 229 | + $"JWT bearer grant response token_type must be 'bearer' per RFC 7523, got '{response.TokenType}'."); |
| 230 | + } |
| 231 | + |
| 232 | + return new TokenContainer |
| 233 | + { |
| 234 | + AccessToken = response.AccessToken, |
| 235 | + TokenType = response.TokenType, |
| 236 | + RefreshToken = response.RefreshToken, |
| 237 | + ExpiresIn = response.ExpiresIn, |
| 238 | + Scope = response.Scope, |
| 239 | + ObtainedAt = DateTimeOffset.UtcNow, |
| 240 | + }; |
| 241 | + } |
| 242 | + |
| 243 | + #endregion |
| 244 | + |
| 245 | + #region Helper: Auth Server Metadata Discovery |
| 246 | + |
| 247 | + private static readonly string[] s_wellKnownPaths = [".well-known/openid-configuration", ".well-known/oauth-authorization-server"]; |
| 248 | + |
| 249 | + /// <summary> |
| 250 | + /// Discovers authorization server metadata from the well-known endpoints. |
| 251 | + /// </summary> |
| 252 | + internal static async Task<AuthorizationServerMetadata> DiscoverAuthServerMetadataAsync( |
| 253 | + Uri issuerUrl, |
| 254 | + HttpClient httpClient, |
| 255 | + CancellationToken cancellationToken) |
| 256 | + { |
| 257 | + var baseUrl = issuerUrl.ToString(); |
| 258 | + if (!baseUrl.EndsWith("/", StringComparison.Ordinal)) |
| 259 | + { |
| 260 | + issuerUrl = new Uri($"{baseUrl}/"); |
| 261 | + } |
| 262 | + |
| 263 | + foreach (var path in s_wellKnownPaths) |
| 264 | + { |
| 265 | + try |
| 266 | + { |
| 267 | + var wellKnownEndpoint = new Uri(issuerUrl, path); |
| 268 | + var response = await httpClient.GetAsync(wellKnownEndpoint, cancellationToken).ConfigureAwait(false); |
| 269 | + |
| 270 | + if (!response.IsSuccessStatusCode) |
| 271 | + { |
| 272 | + continue; |
| 273 | + } |
| 274 | + |
| 275 | + using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| 276 | + var metadata = await JsonSerializer.DeserializeAsync( |
| 277 | + stream, |
| 278 | + McpJsonUtilities.JsonContext.Default.AuthorizationServerMetadata, |
| 279 | + cancellationToken).ConfigureAwait(false); |
| 280 | + |
| 281 | + if (metadata is not null) |
| 282 | + { |
| 283 | + return metadata; |
| 284 | + } |
| 285 | + } |
| 286 | + catch |
| 287 | + { |
| 288 | + continue; |
| 289 | + } |
| 290 | + } |
| 291 | + |
| 292 | + throw new IdentityAssertionGrantException($"Failed to discover authorization server metadata for: {issuerUrl}"); |
| 293 | + } |
| 294 | + |
| 295 | + #endregion |
| 296 | +} |
0 commit comments