| | | 1 | | using Microsoft.AspNetCore.Authentication; |
| | | 2 | | using Microsoft.AspNetCore.Authentication.Cookies; |
| | | 3 | | using Microsoft.AspNetCore.Authorization; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using Kestrun.Authentication; |
| | | 6 | | using Serilog.Events; |
| | | 7 | | using Kestrun.Scripting; |
| | | 8 | | using Microsoft.AspNetCore.Authentication.Negotiate; |
| | | 9 | | using Kestrun.Claims; |
| | | 10 | | using Microsoft.AspNetCore.Authentication.OAuth; |
| | | 11 | | using System.Text.Json; |
| | | 12 | | using System.Security.Claims; |
| | | 13 | | using Microsoft.Extensions.DependencyInjection.Extensions; |
| | | 14 | | using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| | | 15 | | using Microsoft.IdentityModel.Protocols; |
| | | 16 | | using Microsoft.IdentityModel.Protocols.OpenIdConnect; |
| | | 17 | | using Kestrun.OpenApi; |
| | | 18 | | |
| | | 19 | | namespace Kestrun.Hosting; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Provides extension methods for adding authentication schemes to the Kestrun host. |
| | | 23 | | /// </summary> |
| | | 24 | | public static class KestrunHostAuthnExtensions |
| | | 25 | | { |
| | | 26 | | #region Basic Authentication |
| | | 27 | | /// <summary> |
| | | 28 | | /// Adds Basic Authentication to the Kestrun host. |
| | | 29 | | /// <para>Use this for simple username/password authentication.</para> |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 32 | | /// <param name="scheme">The authentication scheme name (e.g. "Basic").</param> |
| | | 33 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 34 | | /// <param name="configure">Optional configuration for BasicAuthenticationOptions.</param> |
| | | 35 | | /// <returns>returns the KestrunHost instance.</returns> |
| | | 36 | | public static KestrunHost AddBasicAuthentication( |
| | | 37 | | this KestrunHost host, |
| | | 38 | | string scheme = AuthenticationDefaults.BasicSchemeName, |
| | | 39 | | string? displayName = AuthenticationDefaults.BasicDisplayName, |
| | | 40 | | Action<BasicAuthenticationOptions>? configure = null |
| | | 41 | | ) |
| | | 42 | | { |
| | | 43 | | // Build a prototype options instance (single source of truth) |
| | 8 | 44 | | var prototype = new BasicAuthenticationOptions { Host = host }; |
| | | 45 | | |
| | | 46 | | // Let the caller mutate the prototype |
| | 8 | 47 | | configure?.Invoke(prototype); |
| | | 48 | | |
| | | 49 | | // Configure validators / claims / OpenAPI on the prototype |
| | 8 | 50 | | ConfigureBasicAuthValidators(host, prototype); |
| | 8 | 51 | | ConfigureBasicIssueClaims(host, prototype); |
| | 8 | 52 | | ConfigureOpenApi(host, scheme, prototype); |
| | | 53 | | // register in host for introspection |
| | 8 | 54 | | _ = host.RegisteredAuthentications.Register(scheme, AuthenticationType.Basic, prototype); |
| | 8 | 55 | | var h = host.AddAuthentication( |
| | 8 | 56 | | defaultScheme: scheme, |
| | 8 | 57 | | buildSchemes: ab => |
| | 8 | 58 | | { |
| | 8 | 59 | | _ = ab.AddScheme<BasicAuthenticationOptions, BasicAuthHandler>( |
| | 8 | 60 | | authenticationScheme: scheme, |
| | 8 | 61 | | displayName: displayName, |
| | 8 | 62 | | configureOptions: opts => |
| | 8 | 63 | | { |
| | 8 | 64 | | // Copy from the prototype into the runtime instance |
| | 6 | 65 | | prototype.ApplyTo(opts); |
| | 8 | 66 | | |
| | 6 | 67 | | host.Logger.Debug("Configured Basic Authentication using scheme {Scheme}", scheme); |
| | 14 | 68 | | }); |
| | 8 | 69 | | } |
| | 8 | 70 | | ); |
| | | 71 | | // register the post-configurer **after** the scheme so it can |
| | | 72 | | // read BasicAuthenticationOptions for <scheme> |
| | 8 | 73 | | return h.AddService(services => |
| | 8 | 74 | | { |
| | 8 | 75 | | _ = services.AddSingleton<IPostConfigureOptions<AuthorizationOptions>>( |
| | 11 | 76 | | sp => new ClaimPolicyPostConfigurer( |
| | 11 | 77 | | scheme, |
| | 11 | 78 | | sp.GetRequiredService< |
| | 11 | 79 | | IOptionsMonitor<BasicAuthenticationOptions>>())); |
| | 16 | 80 | | }); |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Adds Basic Authentication to the Kestrun host using the provided options object. |
| | | 85 | | /// </summary> |
| | | 86 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 87 | | /// <param name="scheme">The authentication scheme name (e.g. "Basic").</param> |
| | | 88 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 89 | | /// <param name="configure">The BasicAuthenticationOptions object to configure the authentication.</param> |
| | | 90 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 91 | | public static KestrunHost AddBasicAuthentication( |
| | | 92 | | this KestrunHost host, |
| | | 93 | | string scheme, |
| | | 94 | | string? displayName, |
| | | 95 | | BasicAuthenticationOptions configure |
| | | 96 | | ) |
| | | 97 | | { |
| | 1 | 98 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 99 | | { |
| | 1 | 100 | | host.Logger.Debug("Adding Basic Authentication with scheme: {Scheme}", scheme); |
| | | 101 | | } |
| | | 102 | | // Ensure the scheme is not null |
| | 1 | 103 | | ArgumentNullException.ThrowIfNull(host); |
| | 1 | 104 | | ArgumentNullException.ThrowIfNull(scheme); |
| | 1 | 105 | | ArgumentNullException.ThrowIfNull(configure); |
| | | 106 | | // Ensure host is set |
| | 1 | 107 | | if (configure.Host != host) |
| | | 108 | | { |
| | 1 | 109 | | configure.Host = host; |
| | | 110 | | } |
| | 1 | 111 | | return host.AddBasicAuthentication( |
| | 1 | 112 | | scheme: scheme, |
| | 1 | 113 | | displayName: displayName, |
| | 1 | 114 | | configure: configure.ApplyTo |
| | 1 | 115 | | ); |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | /// <summary> |
| | | 119 | | /// Configures the validators for Basic authentication. |
| | | 120 | | /// </summary> |
| | | 121 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 122 | | /// <param name="opts">The options to configure.</param> |
| | | 123 | | private static void ConfigureBasicAuthValidators(KestrunHost host, BasicAuthenticationOptions opts) |
| | | 124 | | { |
| | 8 | 125 | | var settings = opts.ValidateCodeSettings; |
| | 8 | 126 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | | 127 | | { |
| | 5 | 128 | | return; |
| | | 129 | | } |
| | | 130 | | |
| | 3 | 131 | | switch (settings.Language) |
| | | 132 | | { |
| | | 133 | | case ScriptLanguage.PowerShell: |
| | 1 | 134 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 135 | | { |
| | 1 | 136 | | opts.Logger.Debug("Building PowerShell validator for Basic authentication"); |
| | | 137 | | } |
| | | 138 | | |
| | 1 | 139 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildPsValidator(host, settings); |
| | 1 | 140 | | break; |
| | | 141 | | case ScriptLanguage.CSharp: |
| | 1 | 142 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 143 | | { |
| | 1 | 144 | | opts.Logger.Debug("Building C# validator for Basic authentication"); |
| | | 145 | | } |
| | | 146 | | |
| | 1 | 147 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildCsValidator(host, settings); |
| | 1 | 148 | | break; |
| | | 149 | | case ScriptLanguage.VBNet: |
| | 1 | 150 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 151 | | { |
| | 1 | 152 | | opts.Logger.Debug("Building VB.NET validator for Basic authentication"); |
| | | 153 | | } |
| | | 154 | | |
| | 1 | 155 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildVBNetValidator(host, settings); |
| | 1 | 156 | | break; |
| | | 157 | | default: |
| | 0 | 158 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 159 | | { |
| | 0 | 160 | | opts.Logger.Warning("No valid language specified for Basic authentication"); |
| | | 161 | | } |
| | | 162 | | break; |
| | | 163 | | } |
| | 0 | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <summary> |
| | | 167 | | /// Configures the issue claims for Basic authentication. |
| | | 168 | | /// </summary> |
| | | 169 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 170 | | /// <param name="opts">The options to configure.</param> |
| | | 171 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | | 172 | | private static void ConfigureBasicIssueClaims(KestrunHost host, BasicAuthenticationOptions opts) |
| | | 173 | | { |
| | 8 | 174 | | var settings = opts.IssueClaimsCodeSettings; |
| | 8 | 175 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | | 176 | | { |
| | 5 | 177 | | return; |
| | | 178 | | } |
| | | 179 | | |
| | 3 | 180 | | switch (settings.Language) |
| | | 181 | | { |
| | | 182 | | case ScriptLanguage.PowerShell: |
| | 1 | 183 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 184 | | { |
| | 1 | 185 | | opts.Logger.Debug("Building PowerShell Issue Claims for API Basic authentication"); |
| | | 186 | | } |
| | | 187 | | |
| | 1 | 188 | | opts.IssueClaims = IAuthHandler.BuildPsIssueClaims(host, settings); |
| | 1 | 189 | | break; |
| | | 190 | | case ScriptLanguage.CSharp: |
| | 1 | 191 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 192 | | { |
| | 1 | 193 | | opts.Logger.Debug("Building C# Issue Claims for API Basic authentication"); |
| | | 194 | | } |
| | | 195 | | |
| | 1 | 196 | | opts.IssueClaims = IAuthHandler.BuildCsIssueClaims(host, settings); |
| | 1 | 197 | | break; |
| | | 198 | | case ScriptLanguage.VBNet: |
| | 1 | 199 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 200 | | { |
| | 1 | 201 | | opts.Logger.Debug("Building VB.NET Issue Claims for API Basic authentication"); |
| | | 202 | | } |
| | | 203 | | |
| | 1 | 204 | | opts.IssueClaims = IAuthHandler.BuildVBNetIssueClaims(host, settings); |
| | 1 | 205 | | break; |
| | | 206 | | default: |
| | 0 | 207 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 208 | | { |
| | 0 | 209 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | | 210 | | } |
| | 0 | 211 | | throw new NotSupportedException("Unsupported language"); |
| | | 212 | | } |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | #endregion |
| | | 216 | | #region GitHub OAuth Authentication |
| | | 217 | | /// <summary> |
| | | 218 | | /// Adds GitHub OAuth (Authorization Code) authentication with optional email enrichment. |
| | | 219 | | /// Creates three schemes: <paramref name="scheme"/>, <paramref name="scheme"/>.Cookies, <paramref name="scheme"/>.P |
| | | 220 | | /// </summary> |
| | | 221 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 222 | | /// <param name="scheme">Base scheme name (e.g. "GitHub").</param> |
| | | 223 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 224 | | /// <param name="documentationId">Documentation IDs for the authentication scheme.</param> |
| | | 225 | | /// <param name="description">A description of the authentication scheme.</param> |
| | | 226 | | /// <param name="deprecated">If true, marks the authentication scheme as deprecated in OpenAPI documentation.</param |
| | | 227 | | /// <param name="clientId">GitHub OAuth App Client ID.</param> |
| | | 228 | | /// <param name="clientSecret">GitHub OAuth App Client Secret.</param> |
| | | 229 | | /// <param name="callbackPath">The callback path for OAuth redirection (e.g. "/signin-github").</param> |
| | | 230 | | /// <returns>The configured KestrunHost.</returns> |
| | | 231 | | public static KestrunHost AddGitHubOAuthAuthentication( |
| | | 232 | | this KestrunHost host, |
| | | 233 | | string scheme, |
| | | 234 | | string? displayName, |
| | | 235 | | string[]? documentationId, |
| | | 236 | | string? description, |
| | | 237 | | bool deprecated, |
| | | 238 | | string clientId, |
| | | 239 | | string clientSecret, |
| | | 240 | | string callbackPath) |
| | | 241 | | { |
| | 0 | 242 | | var opts = ConfigureGitHubOAuth2Options(host, clientId, clientSecret, callbackPath); |
| | 0 | 243 | | ConfigureGitHubClaimMappings(opts); |
| | 0 | 244 | | opts.DocumentationId = documentationId ?? []; |
| | 0 | 245 | | if (!string.IsNullOrWhiteSpace(description)) |
| | | 246 | | { |
| | 0 | 247 | | opts.Description = description; |
| | | 248 | | } |
| | 0 | 249 | | opts.Deprecated = deprecated; |
| | 0 | 250 | | opts.Events = new OAuthEvents |
| | 0 | 251 | | { |
| | 0 | 252 | | OnCreatingTicket = async context => |
| | 0 | 253 | | { |
| | 0 | 254 | | await FetchGitHubUserInfoAsync(context); |
| | 0 | 255 | | await EnrichGitHubEmailClaimAsync(context, host); |
| | 0 | 256 | | } |
| | 0 | 257 | | }; |
| | 0 | 258 | | return host.AddOAuth2Authentication(scheme, displayName, opts); |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | /// <summary> |
| | | 262 | | /// Configures OAuth2Options for GitHub authentication. |
| | | 263 | | /// </summary> |
| | | 264 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 265 | | /// <param name="clientId">GitHub OAuth App Client ID.</param> |
| | | 266 | | /// <param name="clientSecret">GitHub OAuth App Client Secret.</param> |
| | | 267 | | /// <param name="callbackPath">The callback path for OAuth redirection (e.g. "/signin-github").</param> |
| | | 268 | | /// <returns>The configured OAuth2Options.</returns> |
| | | 269 | | private static OAuth2Options ConfigureGitHubOAuth2Options(KestrunHost host, string clientId, string clientSecret, st |
| | | 270 | | { |
| | 0 | 271 | | return new OAuth2Options() |
| | 0 | 272 | | { |
| | 0 | 273 | | Host = host, |
| | 0 | 274 | | ClientId = clientId, |
| | 0 | 275 | | ClientSecret = clientSecret, |
| | 0 | 276 | | CallbackPath = callbackPath, |
| | 0 | 277 | | AuthorizationEndpoint = "https://github.com/login/oauth/authorize", |
| | 0 | 278 | | TokenEndpoint = "https://github.com/login/oauth/access_token", |
| | 0 | 279 | | UserInformationEndpoint = "https://api.github.com/user", |
| | 0 | 280 | | SaveTokens = true, |
| | 0 | 281 | | SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme, |
| | 0 | 282 | | Scope = { "read:user", "user:email" } |
| | 0 | 283 | | }; |
| | | 284 | | } |
| | | 285 | | |
| | | 286 | | /// <summary> |
| | | 287 | | /// Configures claim mappings for GitHub OAuth2Options. |
| | | 288 | | /// </summary> |
| | | 289 | | /// <param name="opts">The OAuth2Options to configure.</param> |
| | | 290 | | private static void ConfigureGitHubClaimMappings(OAuth2Options opts) |
| | | 291 | | { |
| | 0 | 292 | | opts.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); |
| | 0 | 293 | | opts.ClaimActions.MapJsonKey(ClaimTypes.Name, "login"); |
| | 0 | 294 | | opts.ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); |
| | 0 | 295 | | opts.ClaimActions.MapJsonKey("name", "name"); |
| | 0 | 296 | | opts.ClaimActions.MapJsonKey("urn:github:login", "login"); |
| | 0 | 297 | | opts.ClaimActions.MapJsonKey("urn:github:avatar_url", "avatar_url"); |
| | 0 | 298 | | opts.ClaimActions.MapJsonKey("urn:github:html_url", "html_url"); |
| | 0 | 299 | | } |
| | | 300 | | |
| | | 301 | | /// <summary> |
| | | 302 | | /// Fetches GitHub user information and adds claims to the identity. |
| | | 303 | | /// </summary> |
| | | 304 | | /// <param name="context">The OAuthCreatingTicketContext.</param> |
| | | 305 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 306 | | private static async Task FetchGitHubUserInfoAsync(OAuthCreatingTicketContext context) |
| | | 307 | | { |
| | 0 | 308 | | using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); |
| | 0 | 309 | | request.Headers.Accept.Add(new("application/json")); |
| | 0 | 310 | | request.Headers.Add("User-Agent", "KestrunOAuth/1.0"); |
| | 0 | 311 | | request.Headers.Authorization = new("Bearer", context.AccessToken); |
| | | 312 | | |
| | 0 | 313 | | using var response = await context.Backchannel.SendAsync(request, |
| | 0 | 314 | | HttpCompletionOption.ResponseHeadersRead, |
| | 0 | 315 | | context.HttpContext.RequestAborted); |
| | | 316 | | |
| | 0 | 317 | | _ = response.EnsureSuccessStatusCode(); |
| | | 318 | | |
| | 0 | 319 | | using var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.HttpContext.RequestAborted) |
| | 0 | 320 | | context.RunClaimActions(user.RootElement); |
| | 0 | 321 | | } |
| | | 322 | | |
| | | 323 | | /// <summary> |
| | | 324 | | /// Fetches GitHub user emails and enriches the identity with the primary verified email claim. |
| | | 325 | | /// </summary> |
| | | 326 | | /// <param name="context">The OAuthCreatingTicketContext.</param> |
| | | 327 | | /// <param name="host">The KestrunHost instance for logging.</param> |
| | | 328 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 329 | | private static async Task EnrichGitHubEmailClaimAsync(OAuthCreatingTicketContext context, KestrunHost host) |
| | | 330 | | { |
| | 0 | 331 | | if (context.Identity is null || context.Identity.HasClaim(c => c.Type == ClaimTypes.Email)) |
| | | 332 | | { |
| | 0 | 333 | | return; |
| | | 334 | | } |
| | | 335 | | |
| | | 336 | | try |
| | | 337 | | { |
| | 0 | 338 | | using var emailRequest = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/user/emails"); |
| | 0 | 339 | | emailRequest.Headers.Accept.Add(new("application/json")); |
| | 0 | 340 | | emailRequest.Headers.Add("User-Agent", "KestrunOAuth/1.0"); |
| | 0 | 341 | | emailRequest.Headers.Authorization = new("Bearer", context.AccessToken); |
| | | 342 | | |
| | 0 | 343 | | using var emailResponse = await context.Backchannel.SendAsync(emailRequest, |
| | 0 | 344 | | HttpCompletionOption.ResponseHeadersRead, |
| | 0 | 345 | | context.HttpContext.RequestAborted); |
| | | 346 | | |
| | 0 | 347 | | if (!emailResponse.IsSuccessStatusCode) |
| | | 348 | | { |
| | 0 | 349 | | return; |
| | | 350 | | } |
| | | 351 | | |
| | 0 | 352 | | using var emails = JsonDocument.Parse(await emailResponse.Content.ReadAsStringAsync(context.HttpContext.Requ |
| | 0 | 353 | | var primaryEmail = FindPrimaryVerifiedEmail(emails) ?? FindFirstVerifiedEmail(emails); |
| | | 354 | | |
| | 0 | 355 | | if (!string.IsNullOrWhiteSpace(primaryEmail)) |
| | | 356 | | { |
| | 0 | 357 | | context.Identity.AddClaim(new Claim( |
| | 0 | 358 | | ClaimTypes.Email, |
| | 0 | 359 | | primaryEmail, |
| | 0 | 360 | | ClaimValueTypes.String, |
| | 0 | 361 | | context.Options.ClaimsIssuer)); |
| | | 362 | | } |
| | 0 | 363 | | } |
| | 0 | 364 | | catch (Exception ex) |
| | | 365 | | { |
| | 0 | 366 | | host.Logger.Verbose(exception: ex, messageTemplate: "Failed to enrich GitHub email claim."); |
| | 0 | 367 | | } |
| | 0 | 368 | | } |
| | | 369 | | |
| | | 370 | | /// <summary> |
| | | 371 | | /// Finds the primary verified email from the GitHub emails JSON document. |
| | | 372 | | /// </summary> |
| | | 373 | | /// <param name="emails">The JSON document containing GitHub emails.</param> |
| | | 374 | | /// <returns>The primary verified email if found; otherwise, null.</returns> |
| | | 375 | | private static string? FindPrimaryVerifiedEmail(JsonDocument emails) |
| | | 376 | | { |
| | 0 | 377 | | foreach (var emailObj in emails.RootElement.EnumerateArray()) |
| | | 378 | | { |
| | 0 | 379 | | var isPrimary = emailObj.TryGetProperty("primary", out var primaryProp) && primaryProp.GetBoolean(); |
| | 0 | 380 | | var isVerified = emailObj.TryGetProperty("verified", out var verifiedProp) && verifiedProp.GetBoolean(); |
| | | 381 | | |
| | 0 | 382 | | if (isPrimary && isVerified && emailObj.TryGetProperty("email", out var emailProp)) |
| | | 383 | | { |
| | 0 | 384 | | return emailProp.GetString(); |
| | | 385 | | } |
| | | 386 | | } |
| | 0 | 387 | | return null; |
| | 0 | 388 | | } |
| | | 389 | | |
| | | 390 | | /// <summary> |
| | | 391 | | /// Finds the primary verified email from the GitHub emails JSON document. |
| | | 392 | | /// </summary> |
| | | 393 | | /// <param name="emails">The JSON document containing GitHub emails.</param> |
| | | 394 | | /// <returns>The primary verified email if found; otherwise, null.</returns> |
| | | 395 | | private static string? FindFirstVerifiedEmail(JsonDocument emails) |
| | | 396 | | { |
| | 0 | 397 | | foreach (var emailObj in emails.RootElement.EnumerateArray()) |
| | | 398 | | { |
| | 0 | 399 | | var isVerified = emailObj.TryGetProperty("verified", out var verifiedProp) && verifiedProp.GetBoolean(); |
| | 0 | 400 | | if (isVerified && emailObj.TryGetProperty("email", out var emailProp)) |
| | | 401 | | { |
| | 0 | 402 | | return emailProp.GetString(); |
| | | 403 | | } |
| | | 404 | | } |
| | 0 | 405 | | return null; |
| | 0 | 406 | | } |
| | | 407 | | |
| | | 408 | | #endregion |
| | | 409 | | #region JWT Bearer Authentication |
| | | 410 | | /// <summary> |
| | | 411 | | /// Adds JWT Bearer authentication to the Kestrun host. |
| | | 412 | | /// <para>Use this for APIs that require token-based authentication.</para> |
| | | 413 | | /// </summary> |
| | | 414 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 415 | | /// <param name="authenticationScheme">The authentication scheme name (e.g. "Bearer").</param> |
| | | 416 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 417 | | /// <param name="configureOptions">Optional configuration for JwtAuthOptions.</param> |
| | | 418 | | /// <example> |
| | | 419 | | /// HS512 (HMAC-SHA-512, symmetric) |
| | | 420 | | /// </example> |
| | | 421 | | /// <code> |
| | | 422 | | /// var hmacKey = new SymmetricSecurityKey( |
| | | 423 | | /// Encoding.UTF8.GetBytes("32-bytes-or-more-secret……")); |
| | | 424 | | /// host.AddJwtBearerAuthentication( |
| | | 425 | | /// scheme: "Bearer", |
| | | 426 | | /// issuer: "KestrunApi", |
| | | 427 | | /// audience: "KestrunClients", |
| | | 428 | | /// validationKey: hmacKey, |
| | | 429 | | /// validAlgorithms: new[] { SecurityAlgorithms.HmacSha512 }); |
| | | 430 | | /// </code> |
| | | 431 | | /// <example> |
| | | 432 | | /// RS256 (RSA-SHA-256, asymmetric) |
| | | 433 | | /// <para>Requires a PEM-encoded private key file.</para> |
| | | 434 | | /// <code> |
| | | 435 | | /// using var rsa = RSA.Create(); |
| | | 436 | | /// rsa.ImportFromPem(File.ReadAllText("private-key.pem")); |
| | | 437 | | /// var rsaKey = new RsaSecurityKey(rsa); |
| | | 438 | | /// |
| | | 439 | | /// host.AddJwtBearerAuthentication( |
| | | 440 | | /// scheme: "Rs256", |
| | | 441 | | /// issuer: "KestrunApi", |
| | | 442 | | /// audience: "KestrunClients", |
| | | 443 | | /// validationKey: rsaKey, |
| | | 444 | | /// validAlgorithms: new[] { SecurityAlgorithms.RsaSha256 }); |
| | | 445 | | /// </code> |
| | | 446 | | /// </example> |
| | | 447 | | /// <example> |
| | | 448 | | /// ES256 (ECDSA-SHA-256, asymmetric) |
| | | 449 | | /// <para>Requires a PEM-encoded private key file.</para> |
| | | 450 | | /// <code> |
| | | 451 | | /// using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); |
| | | 452 | | /// var esKey = new ECDsaSecurityKey(ecdsa); |
| | | 453 | | /// host.AddJwtBearerAuthentication( |
| | | 454 | | /// "Es256", "KestrunApi", "KestrunClients", |
| | | 455 | | /// esKey, new[] { SecurityAlgorithms.EcdsaSha256 }); |
| | | 456 | | /// </code> |
| | | 457 | | /// </example> |
| | | 458 | | /// <returns></returns> |
| | | 459 | | public static KestrunHost AddJwtBearerAuthentication( |
| | | 460 | | this KestrunHost host, |
| | | 461 | | string authenticationScheme = AuthenticationDefaults.JwtBearerSchemeName, |
| | | 462 | | string? displayName = AuthenticationDefaults.JwtBearerDisplayName, |
| | | 463 | | Action<JwtAuthOptions>? configureOptions = null) |
| | | 464 | | { |
| | 3 | 465 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 466 | | // Build a prototype options instance (single source of truth) |
| | 3 | 467 | | var prototype = new JwtAuthOptions { Host = host }; |
| | 3 | 468 | | configureOptions?.Invoke(prototype); |
| | 3 | 469 | | ConfigureOpenApi(host, authenticationScheme, prototype); |
| | | 470 | | |
| | | 471 | | // register in host for introspection |
| | 3 | 472 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.Bearer, prototype); |
| | | 473 | | |
| | 3 | 474 | | return host.AddAuthentication( |
| | 3 | 475 | | defaultScheme: authenticationScheme, |
| | 3 | 476 | | buildSchemes: ab => |
| | 3 | 477 | | { |
| | 3 | 478 | | _ = ab.AddJwtBearer( |
| | 3 | 479 | | authenticationScheme: authenticationScheme, |
| | 3 | 480 | | displayName: displayName, |
| | 3 | 481 | | configureOptions: opts => |
| | 3 | 482 | | { |
| | 0 | 483 | | prototype.ApplyTo(opts); |
| | 3 | 484 | | }); |
| | 3 | 485 | | }, |
| | 3 | 486 | | configureAuthz: prototype.ClaimPolicy?.ToAuthzDelegate() |
| | 3 | 487 | | ); |
| | | 488 | | } |
| | | 489 | | |
| | | 490 | | /// <summary> |
| | | 491 | | /// Adds JWT Bearer authentication to the Kestrun host using the provided options object. |
| | | 492 | | /// </summary> |
| | | 493 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 494 | | /// <param name="authenticationScheme">The authentication scheme name.</param> |
| | | 495 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 496 | | /// <param name="configureOptions">Optional configuration for JwtAuthOptions.</param> |
| | | 497 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 498 | | public static KestrunHost AddJwtBearerAuthentication( |
| | | 499 | | this KestrunHost host, |
| | | 500 | | string authenticationScheme = AuthenticationDefaults.JwtBearerSchemeName, |
| | | 501 | | string? displayName = AuthenticationDefaults.JwtBearerDisplayName, |
| | | 502 | | JwtAuthOptions? configureOptions = null) |
| | | 503 | | { |
| | 3 | 504 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 505 | | { |
| | 3 | 506 | | host.Logger.Debug("Adding Jwt Bearer Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 507 | | } |
| | | 508 | | // Ensure the scheme is not null |
| | 3 | 509 | | ArgumentNullException.ThrowIfNull(host); |
| | 3 | 510 | | ArgumentNullException.ThrowIfNull(authenticationScheme); |
| | 3 | 511 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 512 | | |
| | | 513 | | // Ensure host is set |
| | 3 | 514 | | if (configureOptions.Host != host) |
| | | 515 | | { |
| | 0 | 516 | | configureOptions.Host = host; |
| | | 517 | | } |
| | | 518 | | |
| | 3 | 519 | | return host.AddJwtBearerAuthentication( |
| | 3 | 520 | | authenticationScheme: authenticationScheme, |
| | 3 | 521 | | displayName: displayName, |
| | 3 | 522 | | configureOptions: opts => |
| | 3 | 523 | | { |
| | 3 | 524 | | // Copy relevant properties from provided options instance to the framework-created one |
| | 3 | 525 | | configureOptions.ApplyTo(opts); |
| | 3 | 526 | | host.Logger.Debug( |
| | 3 | 527 | | "Configured JWT Authentication using scheme {Scheme}.", |
| | 3 | 528 | | authenticationScheme); |
| | 3 | 529 | | } |
| | 3 | 530 | | ); |
| | | 531 | | } |
| | | 532 | | #endregion |
| | | 533 | | #region Cookie Authentication |
| | | 534 | | /// <summary> |
| | | 535 | | /// Adds Cookie Authentication to the Kestrun host. |
| | | 536 | | /// <para>Use this for browser-based authentication using cookies.</para> |
| | | 537 | | /// </summary> |
| | | 538 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 539 | | /// <param name="authenticationScheme">The authentication scheme name (default is CookieAuthenticationDefaults.Authe |
| | | 540 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 541 | | /// <param name="configureOptions">Optional configuration for CookieAuthenticationOptions.</param> |
| | | 542 | | /// <param name="claimPolicy">Optional authorization policy configuration.</param> |
| | | 543 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 544 | | public static KestrunHost AddCookieAuthentication( |
| | | 545 | | this KestrunHost host, |
| | | 546 | | string authenticationScheme = AuthenticationDefaults.CookiesSchemeName, |
| | | 547 | | string? displayName = AuthenticationDefaults.CookiesDisplayName, |
| | | 548 | | Action<CookieAuthOptions>? configureOptions = null, |
| | | 549 | | ClaimPolicyConfig? claimPolicy = null) |
| | | 550 | | { |
| | | 551 | | // Build a prototype options instance (single source of truth) |
| | 2 | 552 | | var prototype = new CookieAuthOptions { Host = host }; |
| | 2 | 553 | | configureOptions?.Invoke(prototype); |
| | 2 | 554 | | ConfigureOpenApi(host, authenticationScheme, prototype); |
| | | 555 | | |
| | | 556 | | // register in host for introspection |
| | 2 | 557 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.Cookie, prototype); |
| | | 558 | | |
| | | 559 | | // Add authentication |
| | 2 | 560 | | return host.AddAuthentication( |
| | 2 | 561 | | defaultScheme: authenticationScheme, |
| | 2 | 562 | | buildSchemes: ab => |
| | 2 | 563 | | { |
| | 2 | 564 | | _ = ab.AddCookie( |
| | 2 | 565 | | authenticationScheme: authenticationScheme, |
| | 2 | 566 | | displayName: displayName, |
| | 2 | 567 | | configureOptions: opts => |
| | 2 | 568 | | { |
| | 2 | 569 | | // Copy everything from the prototype into the real options instance |
| | 0 | 570 | | prototype.ApplyTo(opts); |
| | 2 | 571 | | // let caller mutate everything first |
| | 2 | 572 | | //configure?.Invoke(opts); |
| | 2 | 573 | | }); |
| | 2 | 574 | | }, |
| | 2 | 575 | | configureAuthz: claimPolicy?.ToAuthzDelegate() |
| | 2 | 576 | | ); |
| | | 577 | | } |
| | | 578 | | |
| | | 579 | | /// <summary> |
| | | 580 | | /// Adds Cookie Authentication to the Kestrun host using the provided options object. |
| | | 581 | | /// </summary> |
| | | 582 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 583 | | /// <param name="authenticationScheme">The authentication scheme name (default is CookieAuthenticationDefaults.Authe |
| | | 584 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 585 | | /// <param name="configureOptions">The CookieAuthenticationOptions object to configure the authentication.</param> |
| | | 586 | | /// <param name="claimPolicy">Optional authorization policy configuration.</param> |
| | | 587 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 588 | | public static KestrunHost AddCookieAuthentication( |
| | | 589 | | this KestrunHost host, |
| | | 590 | | string authenticationScheme = AuthenticationDefaults.CookiesSchemeName, |
| | | 591 | | string? displayName = AuthenticationDefaults.CookiesDisplayName, |
| | | 592 | | CookieAuthOptions? configureOptions = null, |
| | | 593 | | ClaimPolicyConfig? claimPolicy = null) |
| | | 594 | | { |
| | 0 | 595 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 596 | | { |
| | 0 | 597 | | host.Logger.Debug("Adding Cookie Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 598 | | } |
| | | 599 | | // Ensure the scheme is not null |
| | 0 | 600 | | ArgumentNullException.ThrowIfNull(host); |
| | 0 | 601 | | ArgumentNullException.ThrowIfNull(authenticationScheme); |
| | 0 | 602 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 603 | | // Ensure host is set |
| | 0 | 604 | | if (configureOptions.Host != host) |
| | | 605 | | { |
| | 0 | 606 | | configureOptions.Host = host; |
| | | 607 | | } |
| | | 608 | | // Copy relevant properties from provided options instance to the framework-created one |
| | 0 | 609 | | return host.AddCookieAuthentication( |
| | 0 | 610 | | authenticationScheme: authenticationScheme, |
| | 0 | 611 | | displayName: displayName, |
| | 0 | 612 | | configureOptions: configureOptions.ApplyTo, |
| | 0 | 613 | | claimPolicy: claimPolicy |
| | 0 | 614 | | ); |
| | | 615 | | } |
| | | 616 | | #endregion |
| | | 617 | | |
| | | 618 | | /* |
| | | 619 | | public static KestrunHost AddClientCertificateAuthentication( |
| | | 620 | | this KestrunHost host, |
| | | 621 | | string scheme = CertificateAuthenticationDefaults.AuthenticationScheme, |
| | | 622 | | Action<CertificateAuthenticationOptions>? configure = null, |
| | | 623 | | Action<AuthorizationOptions>? configureAuthz = null) |
| | | 624 | | { |
| | | 625 | | return host.AddAuthentication( |
| | | 626 | | defaultScheme: scheme, |
| | | 627 | | buildSchemes: ab => |
| | | 628 | | { |
| | | 629 | | ab.AddCertificate( |
| | | 630 | | authenticationScheme: scheme, |
| | | 631 | | configureOptions: configure ?? (opts => { })); |
| | | 632 | | }, |
| | | 633 | | configureAuthz: configureAuthz |
| | | 634 | | ); |
| | | 635 | | } |
| | | 636 | | */ |
| | | 637 | | |
| | | 638 | | #region Windows Authentication |
| | | 639 | | |
| | | 640 | | /// <summary> |
| | | 641 | | /// Adds Windows Authentication to the Kestrun host. |
| | | 642 | | /// <para>The authentication scheme name is <see cref="NegotiateDefaults.AuthenticationScheme"/>. |
| | | 643 | | /// This enables Kerberos and NTLM authentication.</para> |
| | | 644 | | /// </summary> |
| | | 645 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 646 | | /// <param name="authenticationScheme">The authentication scheme name (default is NegotiateDefaults.AuthenticationSc |
| | | 647 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 648 | | /// <param name="configureOptions">The WindowsAuthOptions object to configure the authentication.</param> |
| | | 649 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 650 | | public static KestrunHost AddWindowsAuthentication( |
| | | 651 | | this KestrunHost host, |
| | | 652 | | string authenticationScheme = AuthenticationDefaults.WindowsSchemeName, |
| | | 653 | | string? displayName = AuthenticationDefaults.WindowsDisplayName, |
| | | 654 | | Action<WindowsAuthOptions>? configureOptions = null) |
| | | 655 | | { |
| | | 656 | | // Build a prototype options instance (single source of truth) |
| | 1 | 657 | | var prototype = new WindowsAuthOptions { Host = host }; |
| | 1 | 658 | | configureOptions?.Invoke(prototype); |
| | 1 | 659 | | ConfigureOpenApi(host, authenticationScheme, prototype); |
| | | 660 | | |
| | | 661 | | // register in host for introspection |
| | 1 | 662 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.Cookie, prototype); |
| | | 663 | | |
| | | 664 | | // Add authentication |
| | 1 | 665 | | return host.AddAuthentication( |
| | 1 | 666 | | defaultScheme: authenticationScheme, |
| | 1 | 667 | | buildSchemes: ab => |
| | 1 | 668 | | { |
| | 1 | 669 | | _ = ab.AddNegotiate( |
| | 1 | 670 | | authenticationScheme: authenticationScheme, |
| | 1 | 671 | | displayName: displayName, |
| | 1 | 672 | | configureOptions: opts => |
| | 1 | 673 | | { |
| | 1 | 674 | | // Copy everything from the prototype into the real options instance |
| | 0 | 675 | | prototype.ApplyTo(opts); |
| | 1 | 676 | | |
| | 0 | 677 | | host.Logger.Debug("Configured Windows Authentication using scheme {Scheme}", authenticationSchem |
| | 0 | 678 | | } |
| | 1 | 679 | | ); |
| | 1 | 680 | | } |
| | 1 | 681 | | ); |
| | | 682 | | } |
| | | 683 | | /// <summary> |
| | | 684 | | /// Adds Windows Authentication to the Kestrun host. |
| | | 685 | | /// <para> |
| | | 686 | | /// The authentication scheme name is <see cref="NegotiateDefaults.AuthenticationScheme"/>. |
| | | 687 | | /// This enables Kerberos and NTLM authentication. |
| | | 688 | | /// </para> |
| | | 689 | | /// </summary> |
| | | 690 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 691 | | /// <param name="authenticationScheme">The authentication scheme name (default is NegotiateDefaults.AuthenticationSc |
| | | 692 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 693 | | /// <param name="configureOptions">The WindowsAuthOptions object to configure the authentication.</param> |
| | | 694 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 695 | | public static KestrunHost AddWindowsAuthentication( |
| | | 696 | | this KestrunHost host, |
| | | 697 | | string authenticationScheme = AuthenticationDefaults.WindowsSchemeName, |
| | | 698 | | string? displayName = AuthenticationDefaults.WindowsDisplayName, |
| | | 699 | | WindowsAuthOptions? configureOptions = null) |
| | | 700 | | { |
| | 0 | 701 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 702 | | { |
| | 0 | 703 | | host.Logger.Debug("Adding Windows Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 704 | | } |
| | | 705 | | // Ensure the scheme is not null |
| | 0 | 706 | | ArgumentNullException.ThrowIfNull(host); |
| | 0 | 707 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 708 | | // Ensure host is set |
| | 0 | 709 | | if (configureOptions.Host != host) |
| | | 710 | | { |
| | 0 | 711 | | configureOptions.Host = host; |
| | | 712 | | } |
| | | 713 | | // Copy relevant properties from provided options instance to the framework-created one |
| | | 714 | | // Add authentication |
| | 0 | 715 | | return host.AddWindowsAuthentication( |
| | 0 | 716 | | authenticationScheme: authenticationScheme, |
| | 0 | 717 | | displayName: displayName, |
| | 0 | 718 | | configureOptions: configureOptions.ApplyTo |
| | 0 | 719 | | ); |
| | | 720 | | } |
| | | 721 | | |
| | | 722 | | /// <summary> |
| | | 723 | | /// Adds Windows Authentication to the Kestrun host. |
| | | 724 | | /// <para>The authentication scheme name is <see cref="NegotiateDefaults.AuthenticationScheme"/>. |
| | | 725 | | /// This enables Kerberos and NTLM authentication.</para> |
| | | 726 | | /// </summary> |
| | | 727 | | /// <param name="host"> The Kestrun host instance.</param> |
| | | 728 | | /// <returns> The configured KestrunHost instance.</returns> |
| | | 729 | | public static KestrunHost AddWindowsAuthentication(this KestrunHost host) => |
| | 1 | 730 | | host.AddWindowsAuthentication( |
| | 1 | 731 | | AuthenticationDefaults.WindowsSchemeName, |
| | 1 | 732 | | AuthenticationDefaults.WindowsDisplayName, |
| | 1 | 733 | | (Action<WindowsAuthOptions>?)null); |
| | | 734 | | |
| | | 735 | | #endregion |
| | | 736 | | |
| | | 737 | | #region Client Certificate Authentication |
| | | 738 | | |
| | | 739 | | /// <summary> |
| | | 740 | | /// Adds Client Certificate Authentication to the Kestrun host. |
| | | 741 | | /// <para>Use this for authenticating clients using X.509 certificates.</para> |
| | | 742 | | /// </summary> |
| | | 743 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 744 | | /// <param name="scheme">The authentication scheme name (default is "Certificate").</param> |
| | | 745 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 746 | | /// <param name="configure">Optional configuration for ClientCertificateAuthenticationOptions.</param> |
| | | 747 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 748 | | public static KestrunHost AddClientCertificateAuthentication( |
| | | 749 | | this KestrunHost host, |
| | | 750 | | string scheme = AuthenticationDefaults.CertificateSchemeName, |
| | | 751 | | string? displayName = AuthenticationDefaults.CertificateDisplayName, |
| | | 752 | | Action<ClientCertificateAuthenticationOptions>? configure = null) |
| | | 753 | | { |
| | | 754 | | // Build a prototype options instance (single source of truth) |
| | 1 | 755 | | var prototype = new ClientCertificateAuthenticationOptions { Host = host }; |
| | | 756 | | |
| | | 757 | | // Let the caller mutate the prototype |
| | 1 | 758 | | configure?.Invoke(prototype); |
| | | 759 | | |
| | 1 | 760 | | ConfigureOpenApi(host, scheme, prototype); |
| | | 761 | | |
| | | 762 | | // Register in host for introspection |
| | 1 | 763 | | _ = host.RegisteredAuthentications.Register(scheme, AuthenticationType.Certificate, prototype); |
| | | 764 | | |
| | 1 | 765 | | return host.AddAuthentication( |
| | 1 | 766 | | defaultScheme: scheme, |
| | 1 | 767 | | buildSchemes: ab => |
| | 1 | 768 | | { |
| | 1 | 769 | | _ = ab.AddScheme<ClientCertificateAuthenticationOptions, ClientCertificateAuthHandler>( |
| | 1 | 770 | | authenticationScheme: scheme, |
| | 1 | 771 | | displayName: displayName, |
| | 1 | 772 | | configureOptions: opts => |
| | 1 | 773 | | { |
| | 1 | 774 | | // Copy from the prototype into the runtime instance |
| | 0 | 775 | | prototype.ApplyTo(opts); |
| | 1 | 776 | | |
| | 0 | 777 | | host.Logger.Debug("Configured Client Certificate Authentication using scheme {Scheme}", scheme); |
| | 1 | 778 | | }); |
| | 1 | 779 | | } |
| | 1 | 780 | | ); |
| | | 781 | | } |
| | | 782 | | |
| | | 783 | | /// <summary> |
| | | 784 | | /// Adds Client Certificate Authentication to the Kestrun host using the provided options object. |
| | | 785 | | /// </summary> |
| | | 786 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 787 | | /// <param name="scheme">The authentication scheme name (default is "Certificate").</param> |
| | | 788 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 789 | | /// <param name="configure">The ClientCertificateAuthenticationOptions object to configure the authentication.</para |
| | | 790 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 791 | | public static KestrunHost AddClientCertificateAuthentication( |
| | | 792 | | this KestrunHost host, |
| | | 793 | | string scheme, |
| | | 794 | | string? displayName, |
| | | 795 | | ClientCertificateAuthenticationOptions configure) |
| | | 796 | | { |
| | 0 | 797 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 798 | | { |
| | 0 | 799 | | host.Logger.Debug("Adding Client Certificate Authentication with scheme: {Scheme}", scheme); |
| | | 800 | | } |
| | | 801 | | |
| | | 802 | | // Ensure the scheme is not null |
| | 0 | 803 | | ArgumentNullException.ThrowIfNull(host); |
| | 0 | 804 | | ArgumentNullException.ThrowIfNull(scheme); |
| | 0 | 805 | | ArgumentNullException.ThrowIfNull(configure); |
| | | 806 | | |
| | | 807 | | // Ensure host is set |
| | 0 | 808 | | if (configure.Host != host) |
| | | 809 | | { |
| | 0 | 810 | | configure.Host = host; |
| | | 811 | | } |
| | | 812 | | |
| | 0 | 813 | | return host.AddClientCertificateAuthentication( |
| | 0 | 814 | | scheme: scheme, |
| | 0 | 815 | | displayName: displayName, |
| | 0 | 816 | | configure: configure.ApplyTo |
| | 0 | 817 | | ); |
| | | 818 | | } |
| | | 819 | | |
| | | 820 | | /// <summary> |
| | | 821 | | /// Adds Client Certificate Authentication to the Kestrun host with default settings. |
| | | 822 | | /// </summary> |
| | | 823 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 824 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 825 | | public static KestrunHost AddClientCertificateAuthentication(this KestrunHost host) => |
| | 0 | 826 | | host.AddClientCertificateAuthentication( |
| | 0 | 827 | | AuthenticationDefaults.CertificateSchemeName, |
| | 0 | 828 | | AuthenticationDefaults.CertificateDisplayName, |
| | 0 | 829 | | (Action<ClientCertificateAuthenticationOptions>?)null); |
| | | 830 | | |
| | | 831 | | #endregion |
| | | 832 | | #region API Key Authentication |
| | | 833 | | /// <summary> |
| | | 834 | | /// Adds API Key Authentication to the Kestrun host. |
| | | 835 | | /// <para>Use this for endpoints that require an API key for access.</para> |
| | | 836 | | /// </summary> |
| | | 837 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 838 | | /// <param name="authenticationScheme">The authentication scheme name (default is "ApiKey").</param> |
| | | 839 | | /// <param name="displayName">The display name for the authentication scheme (default is "API Key").</param> |
| | | 840 | | /// <param name="configureOptions">Optional configuration for ApiKeyAuthenticationOptions.</param> |
| | | 841 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 842 | | public static KestrunHost AddApiKeyAuthentication( |
| | | 843 | | this KestrunHost host, |
| | | 844 | | string authenticationScheme = AuthenticationDefaults.ApiKeySchemeName, |
| | | 845 | | string? displayName = AuthenticationDefaults.ApiKeyDisplayName, |
| | | 846 | | Action<ApiKeyAuthenticationOptions>? configureOptions = null) |
| | | 847 | | { |
| | | 848 | | // Build a prototype options instance (single source of truth) |
| | 6 | 849 | | var prototype = new ApiKeyAuthenticationOptions { Host = host }; |
| | | 850 | | |
| | | 851 | | // Let the caller mutate the prototype |
| | 6 | 852 | | configureOptions?.Invoke(prototype); |
| | | 853 | | |
| | | 854 | | // Configure validators / claims / OpenAPI on the prototype |
| | 6 | 855 | | ConfigureApiKeyValidators(host, prototype); |
| | 6 | 856 | | ConfigureApiKeyIssueClaims(host, prototype); |
| | 6 | 857 | | ConfigureOpenApi(host, authenticationScheme, prototype); |
| | | 858 | | |
| | | 859 | | // register in host for introspection |
| | 6 | 860 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.ApiKey, prototype); |
| | | 861 | | // Add authentication |
| | 6 | 862 | | return host.AddAuthentication( |
| | 6 | 863 | | defaultScheme: authenticationScheme, |
| | 6 | 864 | | buildSchemes: ab => |
| | 6 | 865 | | { |
| | 6 | 866 | | // ← TOptions == ApiKeyAuthenticationOptions |
| | 6 | 867 | | // THandler == ApiKeyAuthHandler |
| | 6 | 868 | | _ = ab.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthHandler>( |
| | 6 | 869 | | authenticationScheme: authenticationScheme, |
| | 6 | 870 | | displayName: displayName, |
| | 6 | 871 | | configureOptions: opts => |
| | 6 | 872 | | { |
| | 6 | 873 | | // Copy from the prototype into the runtime instance |
| | 6 | 874 | | prototype.ApplyTo(opts); |
| | 6 | 875 | | |
| | 6 | 876 | | host.Logger.Debug( |
| | 6 | 877 | | "Configured API Key Authentication using scheme {Scheme} with header {Header} (In={In})", |
| | 6 | 878 | | authenticationScheme, prototype.ApiKeyName, prototype.In); |
| | 12 | 879 | | }); |
| | 6 | 880 | | } |
| | 6 | 881 | | ) |
| | 6 | 882 | | // register the post-configurer **after** the scheme so it can |
| | 6 | 883 | | // read BasicAuthenticationOptions for <scheme> |
| | 6 | 884 | | .AddService(services => |
| | 6 | 885 | | { |
| | 6 | 886 | | _ = services.AddSingleton<IPostConfigureOptions<AuthorizationOptions>>( |
| | 9 | 887 | | sp => new ClaimPolicyPostConfigurer( |
| | 9 | 888 | | authenticationScheme, |
| | 9 | 889 | | sp.GetRequiredService< |
| | 9 | 890 | | IOptionsMonitor<ApiKeyAuthenticationOptions>>())); |
| | 12 | 891 | | }); |
| | | 892 | | } |
| | | 893 | | |
| | | 894 | | /// <summary> |
| | | 895 | | /// Adds API Key Authentication to the Kestrun host using the provided options object. |
| | | 896 | | /// </summary> |
| | | 897 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 898 | | /// <param name="authenticationScheme">The authentication scheme name.</param> |
| | | 899 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 900 | | /// <param name="configureOptions">The ApiKeyAuthenticationOptions object to configure the authentication.</param> |
| | | 901 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 902 | | public static KestrunHost AddApiKeyAuthentication( |
| | | 903 | | this KestrunHost host, |
| | | 904 | | string authenticationScheme = AuthenticationDefaults.ApiKeySchemeName, |
| | | 905 | | string? displayName = AuthenticationDefaults.ApiKeyDisplayName, |
| | | 906 | | ApiKeyAuthenticationOptions? configureOptions = null) |
| | | 907 | | { |
| | 1 | 908 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 909 | | { |
| | 1 | 910 | | host.Logger.Debug("Adding API Key Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 911 | | } |
| | | 912 | | // Ensure the scheme is not null |
| | 1 | 913 | | ArgumentNullException.ThrowIfNull(host); |
| | 1 | 914 | | ArgumentNullException.ThrowIfNull(authenticationScheme); |
| | 1 | 915 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 916 | | // Ensure host is set |
| | 1 | 917 | | if (configureOptions.Host != host) |
| | | 918 | | { |
| | 1 | 919 | | configureOptions.Host = host; |
| | | 920 | | } |
| | | 921 | | // Copy properties from the provided configure object |
| | 1 | 922 | | return host.AddApiKeyAuthentication( |
| | 1 | 923 | | authenticationScheme: authenticationScheme, |
| | 1 | 924 | | displayName: displayName, |
| | 1 | 925 | | configureOptions: configureOptions.ApplyTo |
| | 1 | 926 | | ); |
| | | 927 | | } |
| | | 928 | | |
| | | 929 | | /// <summary> |
| | | 930 | | /// Configures the API Key validators. |
| | | 931 | | /// </summary> |
| | | 932 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 933 | | /// <param name="opts">The options to configure.</param> |
| | | 934 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | | 935 | | private static void ConfigureApiKeyValidators(KestrunHost host, ApiKeyAuthenticationOptions opts) |
| | | 936 | | { |
| | 6 | 937 | | var settings = opts.ValidateCodeSettings; |
| | 6 | 938 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | | 939 | | { |
| | 3 | 940 | | return; |
| | | 941 | | } |
| | | 942 | | |
| | 3 | 943 | | switch (settings.Language) |
| | | 944 | | { |
| | | 945 | | case ScriptLanguage.PowerShell: |
| | 1 | 946 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 947 | | { |
| | 1 | 948 | | opts.Logger.Debug("Building PowerShell validator for API Key authentication"); |
| | | 949 | | } |
| | | 950 | | |
| | 1 | 951 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildPsValidator(host, settings); |
| | 1 | 952 | | break; |
| | | 953 | | case ScriptLanguage.CSharp: |
| | 1 | 954 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 955 | | { |
| | 1 | 956 | | opts.Logger.Debug("Building C# validator for API Key authentication"); |
| | | 957 | | } |
| | | 958 | | |
| | 1 | 959 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildCsValidator(host, settings); |
| | 1 | 960 | | break; |
| | | 961 | | case ScriptLanguage.VBNet: |
| | 1 | 962 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 963 | | { |
| | 1 | 964 | | opts.Logger.Debug("Building VB.NET validator for API Key authentication"); |
| | | 965 | | } |
| | | 966 | | |
| | 1 | 967 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildVBNetValidator(host, settings); |
| | 1 | 968 | | break; |
| | | 969 | | default: |
| | 0 | 970 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 971 | | { |
| | 0 | 972 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | | 973 | | } |
| | 0 | 974 | | throw new NotSupportedException("Unsupported language"); |
| | | 975 | | } |
| | | 976 | | } |
| | | 977 | | |
| | | 978 | | /// <summary> |
| | | 979 | | /// Configures the API Key issue claims. |
| | | 980 | | /// </summary> |
| | | 981 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 982 | | /// <param name="opts">The options to configure.</param> |
| | | 983 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | | 984 | | private static void ConfigureApiKeyIssueClaims(KestrunHost host, ApiKeyAuthenticationOptions opts) |
| | | 985 | | { |
| | 6 | 986 | | var settings = opts.IssueClaimsCodeSettings; |
| | 6 | 987 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | | 988 | | { |
| | 3 | 989 | | return; |
| | | 990 | | } |
| | | 991 | | |
| | 3 | 992 | | switch (settings.Language) |
| | | 993 | | { |
| | | 994 | | case ScriptLanguage.PowerShell: |
| | 1 | 995 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 996 | | { |
| | 1 | 997 | | opts.Logger.Debug("Building PowerShell Issue Claims for API Key authentication"); |
| | | 998 | | } |
| | | 999 | | |
| | 1 | 1000 | | opts.IssueClaims = IAuthHandler.BuildPsIssueClaims(host, settings); |
| | 1 | 1001 | | break; |
| | | 1002 | | case ScriptLanguage.CSharp: |
| | 1 | 1003 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1004 | | { |
| | 1 | 1005 | | opts.Logger.Debug("Building C# Issue Claims for API Key authentication"); |
| | | 1006 | | } |
| | | 1007 | | |
| | 1 | 1008 | | opts.IssueClaims = IAuthHandler.BuildCsIssueClaims(host, settings); |
| | 1 | 1009 | | break; |
| | | 1010 | | case ScriptLanguage.VBNet: |
| | 1 | 1011 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1012 | | { |
| | 1 | 1013 | | opts.Logger.Debug("Building VB.NET Issue Claims for API Key authentication"); |
| | | 1014 | | } |
| | | 1015 | | |
| | 1 | 1016 | | opts.IssueClaims = IAuthHandler.BuildVBNetIssueClaims(host, settings); |
| | 1 | 1017 | | break; |
| | | 1018 | | default: |
| | 0 | 1019 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 1020 | | { |
| | 0 | 1021 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | | 1022 | | } |
| | 0 | 1023 | | throw new NotSupportedException("Unsupported language"); |
| | | 1024 | | } |
| | | 1025 | | } |
| | | 1026 | | |
| | | 1027 | | #endregion |
| | | 1028 | | |
| | | 1029 | | #region OAuth2 Authentication |
| | | 1030 | | |
| | | 1031 | | /// <summary> |
| | | 1032 | | /// Adds OAuth2 authentication to the Kestrun host. |
| | | 1033 | | /// <para>Use this for applications that require OAuth2 authentication.</para> |
| | | 1034 | | /// </summary> |
| | | 1035 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1036 | | /// <param name="authenticationScheme">The authentication scheme name.</param> |
| | | 1037 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 1038 | | /// <param name="configureOptions">The OAuth2Options to configure the authentication.</param> |
| | | 1039 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 1040 | | public static KestrunHost AddOAuth2Authentication( |
| | | 1041 | | this KestrunHost host, |
| | | 1042 | | string authenticationScheme = AuthenticationDefaults.OAuth2SchemeName, |
| | | 1043 | | string? displayName = AuthenticationDefaults.OAuth2DisplayName, |
| | | 1044 | | OAuth2Options? configureOptions = null) |
| | | 1045 | | { |
| | 0 | 1046 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1047 | | { |
| | 0 | 1048 | | host.Logger.Debug("Adding OAuth2 Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 1049 | | } |
| | | 1050 | | // Ensure the scheme is not null |
| | 0 | 1051 | | ArgumentNullException.ThrowIfNull(host); |
| | 0 | 1052 | | ArgumentNullException.ThrowIfNull(authenticationScheme); |
| | 0 | 1053 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 1054 | | |
| | | 1055 | | // Required for OAuth2 |
| | 0 | 1056 | | if (string.IsNullOrWhiteSpace(configureOptions.ClientId)) |
| | | 1057 | | { |
| | 0 | 1058 | | throw new ArgumentException("ClientId must be provided in OAuth2Options", nameof(configureOptions)); |
| | | 1059 | | } |
| | | 1060 | | |
| | 0 | 1061 | | if (string.IsNullOrWhiteSpace(configureOptions.AuthorizationEndpoint)) |
| | | 1062 | | { |
| | 0 | 1063 | | throw new ArgumentException("AuthorizationEndpoint must be provided in OAuth2Options", nameof(configureOptio |
| | | 1064 | | } |
| | | 1065 | | |
| | 0 | 1066 | | if (string.IsNullOrWhiteSpace(configureOptions.TokenEndpoint)) |
| | | 1067 | | { |
| | 0 | 1068 | | throw new ArgumentException("TokenEndpoint must be provided in OAuth2Options", nameof(configureOptions)); |
| | | 1069 | | } |
| | | 1070 | | |
| | | 1071 | | // Default CallbackPath if not set: /signin-{scheme} |
| | 0 | 1072 | | if (string.IsNullOrWhiteSpace(configureOptions.CallbackPath)) |
| | | 1073 | | { |
| | 0 | 1074 | | configureOptions.CallbackPath = $"/signin-{authenticationScheme.ToLowerInvariant()}"; |
| | | 1075 | | } |
| | | 1076 | | // Ensure host is set |
| | 0 | 1077 | | if (configureOptions.Host != host) |
| | | 1078 | | { |
| | 0 | 1079 | | configureOptions.Host = host; |
| | | 1080 | | } |
| | | 1081 | | // Ensure scheme is set |
| | 0 | 1082 | | if (authenticationScheme != configureOptions.AuthenticationScheme) |
| | | 1083 | | { |
| | 0 | 1084 | | configureOptions.AuthenticationScheme = authenticationScheme; |
| | | 1085 | | } |
| | | 1086 | | // Configure scopes and claim policies |
| | 0 | 1087 | | ConfigureScopes(configureOptions, host.Logger); |
| | | 1088 | | // Configure OpenAPI |
| | 0 | 1089 | | ConfigureOpenApi(host, authenticationScheme, configureOptions); |
| | | 1090 | | |
| | | 1091 | | // register in host for introspection |
| | 0 | 1092 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.OAuth2, configureOptions); |
| | | 1093 | | |
| | | 1094 | | // Add authentication |
| | 0 | 1095 | | return host.AddAuthentication( |
| | 0 | 1096 | | defaultScheme: configureOptions.CookieScheme, |
| | 0 | 1097 | | defaultChallengeScheme: authenticationScheme, |
| | 0 | 1098 | | buildSchemes: ab => |
| | 0 | 1099 | | { |
| | 0 | 1100 | | // Add cookie scheme for sign-in |
| | 0 | 1101 | | _ = ab.AddCookie(configureOptions.CookieScheme, cookieOpts => |
| | 0 | 1102 | | { |
| | 0 | 1103 | | configureOptions.CookieOptions.ApplyTo(cookieOpts); |
| | 0 | 1104 | | }); |
| | 0 | 1105 | | // Add OAuth2 scheme |
| | 0 | 1106 | | _ = ab.AddOAuth( |
| | 0 | 1107 | | authenticationScheme: authenticationScheme, |
| | 0 | 1108 | | displayName: displayName ?? OAuthDefaults.DisplayName, |
| | 0 | 1109 | | configureOptions: oauthOpts => |
| | 0 | 1110 | | { |
| | 0 | 1111 | | configureOptions.ApplyTo(oauthOpts); |
| | 0 | 1112 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 0 | 1113 | | { |
| | 0 | 1114 | | host.Logger.Debug("Configured OpenID Connect with ClientId: {ClientId}, Scopes: {Scopes}", |
| | 0 | 1115 | | oauthOpts.ClientId, string.Join(", ", oauthOpts.Scope)); |
| | 0 | 1116 | | } |
| | 0 | 1117 | | }); |
| | 0 | 1118 | | }, |
| | 0 | 1119 | | configureAuthz: configureOptions.ClaimPolicy?.ToAuthzDelegate() |
| | 0 | 1120 | | ); |
| | | 1121 | | } |
| | | 1122 | | |
| | | 1123 | | /// <summary> |
| | | 1124 | | /// Configures OAuth2 scopes and claim policies. |
| | | 1125 | | /// </summary> |
| | | 1126 | | /// <param name="configureOptions">The OAuth2 options to configure.</param> |
| | | 1127 | | /// <param name="logger">The logger for debug output.</param> |
| | | 1128 | | private static void ConfigureScopes(IOAuthCommonOptions configureOptions, Serilog.ILogger logger) |
| | | 1129 | | { |
| | 3 | 1130 | | if (configureOptions.Scope is null) |
| | | 1131 | | { |
| | 0 | 1132 | | return; |
| | | 1133 | | } |
| | | 1134 | | |
| | 3 | 1135 | | if (configureOptions.Scope.Count == 0) |
| | | 1136 | | { |
| | 1 | 1137 | | BackfillScopesFromClaimPolicy(configureOptions, logger); |
| | 1 | 1138 | | return; |
| | | 1139 | | } |
| | | 1140 | | |
| | 2 | 1141 | | LogConfiguredScopes(configureOptions.Scope, logger); |
| | | 1142 | | |
| | 2 | 1143 | | if (configureOptions.ClaimPolicy is null) |
| | | 1144 | | { |
| | 1 | 1145 | | configureOptions.ClaimPolicy = BuildClaimPolicyFromScopes(configureOptions.Scope, logger); |
| | 1 | 1146 | | return; |
| | | 1147 | | } |
| | | 1148 | | |
| | 1 | 1149 | | AddMissingScopesToClaimPolicy(configureOptions.Scope, configureOptions.ClaimPolicy, logger); |
| | 1 | 1150 | | } |
| | | 1151 | | |
| | | 1152 | | private static ClaimPolicyConfig BuildClaimPolicyFromScopes(ICollection<string> scopes, Serilog.ILogger logger) |
| | | 1153 | | { |
| | 1 | 1154 | | var claimPolicyBuilder = new ClaimPolicyBuilder(); |
| | 6 | 1155 | | foreach (var scope in scopes) |
| | | 1156 | | { |
| | 2 | 1157 | | LogScopeAdded(logger, scope); |
| | 2 | 1158 | | _ = claimPolicyBuilder.AddPolicy(policyName: scope, claimType: "scope", description: string.Empty, allowedVa |
| | | 1159 | | } |
| | | 1160 | | |
| | 1 | 1161 | | return claimPolicyBuilder.Build(); |
| | | 1162 | | } |
| | | 1163 | | |
| | | 1164 | | private static void AddMissingScopesToClaimPolicy(ICollection<string> scopes, ClaimPolicyConfig claimPolicy, Serilog |
| | | 1165 | | { |
| | 1 | 1166 | | var missingScopes = scopes |
| | 2 | 1167 | | .Where(s => !claimPolicy.Policies.ContainsKey(s)) |
| | 1 | 1168 | | .ToList(); |
| | | 1169 | | |
| | 1 | 1170 | | if (missingScopes.Count == 0) |
| | | 1171 | | { |
| | 0 | 1172 | | return; |
| | | 1173 | | } |
| | | 1174 | | |
| | 1 | 1175 | | LogMissingScopes(missingScopes, logger); |
| | | 1176 | | |
| | 1 | 1177 | | var claimPolicyBuilder = new ClaimPolicyBuilder(); |
| | 4 | 1178 | | foreach (var scope in missingScopes) |
| | | 1179 | | { |
| | 1 | 1180 | | _ = claimPolicyBuilder.AddPolicy(policyName: scope, claimType: "scope", description: string.Empty, allowedVa |
| | 1 | 1181 | | LogScopeAddedToClaimPolicy(logger, scope); |
| | | 1182 | | } |
| | | 1183 | | |
| | 1 | 1184 | | claimPolicy.AddPolicies(claimPolicyBuilder.Policies); |
| | 1 | 1185 | | } |
| | | 1186 | | |
| | | 1187 | | private static void BackfillScopesFromClaimPolicy(IOAuthCommonOptions configureOptions, Serilog.ILogger logger) |
| | | 1188 | | { |
| | 1 | 1189 | | if (configureOptions.ClaimPolicy is null) |
| | | 1190 | | { |
| | 0 | 1191 | | return; |
| | | 1192 | | } |
| | | 1193 | | |
| | 6 | 1194 | | foreach (var policy in configureOptions.ClaimPolicy.PolicyNames) |
| | | 1195 | | { |
| | 2 | 1196 | | LogClaimPolicyConfigured(logger, policy); |
| | 2 | 1197 | | configureOptions.Scope?.Add(policy); |
| | | 1198 | | } |
| | 1 | 1199 | | } |
| | | 1200 | | |
| | | 1201 | | private static void LogScopeAdded(Serilog.ILogger logger, string scope) |
| | | 1202 | | { |
| | 2 | 1203 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1204 | | { |
| | 2 | 1205 | | logger.Debug("OAuth2 scope added: {Scope}", scope); |
| | | 1206 | | } |
| | 2 | 1207 | | } |
| | | 1208 | | |
| | | 1209 | | private static void LogScopeAddedToClaimPolicy(Serilog.ILogger logger, string scope) |
| | | 1210 | | { |
| | 1 | 1211 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1212 | | { |
| | 1 | 1213 | | logger.Debug("OAuth2 scope added to claim policy: {Scope}", scope); |
| | | 1214 | | } |
| | 1 | 1215 | | } |
| | | 1216 | | |
| | | 1217 | | private static void LogMissingScopes(IEnumerable<string> missingScopes, Serilog.ILogger logger) |
| | | 1218 | | { |
| | 1 | 1219 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1220 | | { |
| | 1 | 1221 | | logger.Debug("Adding missing OAuth2 scopes to claim policy: {Scopes}", string.Join(", ", missingScopes)); |
| | | 1222 | | } |
| | 1 | 1223 | | } |
| | | 1224 | | |
| | | 1225 | | private static void LogConfiguredScopes(IEnumerable<string> scopes, Serilog.ILogger logger) |
| | | 1226 | | { |
| | 2 | 1227 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1228 | | { |
| | 2 | 1229 | | logger.Debug("OAuth2 scopes configured: {Scopes}", string.Join(", ", scopes)); |
| | | 1230 | | } |
| | 2 | 1231 | | } |
| | | 1232 | | |
| | | 1233 | | private static void LogClaimPolicyConfigured(Serilog.ILogger logger, string policy) |
| | | 1234 | | { |
| | 2 | 1235 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1236 | | { |
| | 2 | 1237 | | logger.Debug("OAuth2 claim policy configured: {Policy}", policy); |
| | | 1238 | | } |
| | 2 | 1239 | | } |
| | | 1240 | | |
| | | 1241 | | #endregion |
| | | 1242 | | #region OpenID Connect Authentication |
| | | 1243 | | |
| | | 1244 | | /// <summary> |
| | | 1245 | | /// Adds OpenID Connect authentication to the Kestrun host with private key JWT client assertion. |
| | | 1246 | | /// <para>Use this for applications that require OpenID Connect authentication with client credentials using JWT ass |
| | | 1247 | | /// </summary> |
| | | 1248 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1249 | | /// <param name="authenticationScheme">The authentication scheme name.</param> |
| | | 1250 | | /// <param name="displayName">The display name for the authentication scheme.</param> |
| | | 1251 | | /// <param name="configureOptions">The OpenIdConnectOptions to configure the authentication.</param> |
| | | 1252 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 1253 | | public static KestrunHost AddOpenIdConnectAuthentication( |
| | | 1254 | | this KestrunHost host, |
| | | 1255 | | string authenticationScheme = AuthenticationDefaults.OidcSchemeName, |
| | | 1256 | | string? displayName = AuthenticationDefaults.OidcDisplayName, |
| | | 1257 | | OidcOptions? configureOptions = null) |
| | | 1258 | | { |
| | 0 | 1259 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1260 | | { |
| | 0 | 1261 | | host.Logger.Debug("Adding OpenID Connect Authentication with scheme: {Scheme}", authenticationScheme); |
| | | 1262 | | } |
| | | 1263 | | // Ensure the scheme is not null |
| | 0 | 1264 | | ArgumentNullException.ThrowIfNull(host); |
| | 0 | 1265 | | ArgumentNullException.ThrowIfNull(authenticationScheme); |
| | 0 | 1266 | | ArgumentNullException.ThrowIfNull(configureOptions); |
| | | 1267 | | |
| | | 1268 | | // Ensure ClientId is set |
| | 0 | 1269 | | if (string.IsNullOrWhiteSpace(configureOptions.ClientId)) |
| | | 1270 | | { |
| | 0 | 1271 | | throw new ArgumentException("ClientId must be provided in OpenIdConnectOptions", nameof(configureOptions)); |
| | | 1272 | | } |
| | | 1273 | | // Ensure host is set |
| | 0 | 1274 | | if (configureOptions.Host != host) |
| | | 1275 | | { |
| | 0 | 1276 | | configureOptions.Host = host; |
| | | 1277 | | } |
| | | 1278 | | // Ensure scheme is set |
| | 0 | 1279 | | if (authenticationScheme != configureOptions.AuthenticationScheme) |
| | | 1280 | | { |
| | 0 | 1281 | | configureOptions.AuthenticationScheme = authenticationScheme; |
| | | 1282 | | } |
| | | 1283 | | // Retrieve supported scopes from the OIDC provider |
| | 0 | 1284 | | if (!string.IsNullOrWhiteSpace(configureOptions.Authority)) |
| | | 1285 | | { |
| | 0 | 1286 | | configureOptions.ClaimPolicy = GetSupportedScopes(configureOptions.Authority, host.Logger); |
| | 0 | 1287 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1288 | | { |
| | 0 | 1289 | | host.Logger.Debug("OIDC supported scopes: {Scopes}", string.Join(", ", configureOptions.ClaimPolicy?.Pol |
| | | 1290 | | } |
| | | 1291 | | } |
| | | 1292 | | // Configure scopes and claim policies |
| | 0 | 1293 | | ConfigureScopes(configureOptions, host.Logger); |
| | | 1294 | | // Configure OpenAPI |
| | 0 | 1295 | | ConfigureOpenApi(host, authenticationScheme, configureOptions); |
| | | 1296 | | |
| | | 1297 | | // register in host for introspection |
| | 0 | 1298 | | _ = host.RegisteredAuthentications.Register(authenticationScheme, AuthenticationType.Oidc, configureOptions); |
| | | 1299 | | |
| | | 1300 | | // CRITICAL: Register OidcEvents and AssertionService in DI before configuring authentication |
| | | 1301 | | // This is required because EventsType expects these to be available in the service provider |
| | 0 | 1302 | | return host.AddService(services => |
| | 0 | 1303 | | { |
| | 0 | 1304 | | // Register AssertionService as a singleton with factory to pass clientId and jwkJson |
| | 0 | 1305 | | // Only register if JwkJson is provided (for private_key_jwt authentication) |
| | 0 | 1306 | | if (!string.IsNullOrWhiteSpace(configureOptions.JwkJson)) |
| | 0 | 1307 | | { |
| | 0 | 1308 | | services.TryAddSingleton(sp => new AssertionService(configureOptions.ClientId, configureOptions.JwkJson |
| | 0 | 1309 | | // Register OidcEvents as scoped (per-request) |
| | 0 | 1310 | | services.TryAddScoped<OidcEvents>(); |
| | 0 | 1311 | | } |
| | 0 | 1312 | | }).AddAuthentication( |
| | 0 | 1313 | | defaultScheme: configureOptions.CookieScheme, |
| | 0 | 1314 | | defaultChallengeScheme: authenticationScheme, |
| | 0 | 1315 | | buildSchemes: ab => |
| | 0 | 1316 | | { |
| | 0 | 1317 | | // Add cookie scheme for sign-in |
| | 0 | 1318 | | _ = ab.AddCookie(configureOptions.CookieScheme, cookieOpts => |
| | 0 | 1319 | | { |
| | 0 | 1320 | | // Copy cookie configuration from options.CookieOptions |
| | 0 | 1321 | | configureOptions.CookieOptions.ApplyTo(cookieOpts); |
| | 0 | 1322 | | }); |
| | 0 | 1323 | | // Add OpenID Connect scheme |
| | 0 | 1324 | | _ = ab.AddOpenIdConnect( |
| | 0 | 1325 | | authenticationScheme: authenticationScheme, |
| | 0 | 1326 | | displayName: displayName ?? OpenIdConnectDefaults.DisplayName, |
| | 0 | 1327 | | configureOptions: oidcOpts => |
| | 0 | 1328 | | { |
| | 0 | 1329 | | // Copy all properties from the provided options to the framework's options |
| | 0 | 1330 | | configureOptions.ApplyTo(oidcOpts); |
| | 0 | 1331 | | |
| | 0 | 1332 | | // Inject private key JWT at code → token step (only if JwkJson is provided) |
| | 0 | 1333 | | // This will be resolved from DI at runtime |
| | 0 | 1334 | | if (!string.IsNullOrWhiteSpace(configureOptions.JwkJson)) |
| | 0 | 1335 | | { |
| | 0 | 1336 | | oidcOpts.EventsType = typeof(OidcEvents); |
| | 0 | 1337 | | } |
| | 0 | 1338 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 0 | 1339 | | { |
| | 0 | 1340 | | host.Logger.Debug("Configured OpenID Connect with Authority: {Authority}, ClientId: {ClientId}, |
| | 0 | 1341 | | oidcOpts.Authority, oidcOpts.ClientId, string.Join(", ", oidcOpts.Scope)); |
| | 0 | 1342 | | } |
| | 0 | 1343 | | }); |
| | 0 | 1344 | | }, |
| | 0 | 1345 | | configureAuthz: configureOptions.ClaimPolicy?.ToAuthzDelegate() |
| | 0 | 1346 | | ); |
| | | 1347 | | } |
| | | 1348 | | |
| | | 1349 | | /// <summary> |
| | | 1350 | | /// Retrieves the supported scopes from the OpenID Connect provider's metadata. |
| | | 1351 | | /// </summary> |
| | | 1352 | | /// <param name="authority">The authority URL of the OpenID Connect provider.</param> |
| | | 1353 | | /// <param name="logger">The logger instance for logging.</param> |
| | | 1354 | | /// <returns>A ClaimPolicyConfig containing the supported scopes, or null if retrieval fails.</returns> |
| | | 1355 | | private static ClaimPolicyConfig? GetSupportedScopes(string authority, Serilog.ILogger logger) |
| | | 1356 | | { |
| | 0 | 1357 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1358 | | { |
| | 0 | 1359 | | logger.Debug("Retrieving OpenID Connect configuration from authority: {Authority}", authority); |
| | | 1360 | | } |
| | 0 | 1361 | | var claimPolicy = new ClaimPolicyBuilder(); |
| | 0 | 1362 | | if (string.IsNullOrWhiteSpace(authority)) |
| | | 1363 | | { |
| | 0 | 1364 | | throw new ArgumentException("Authority must be provided to retrieve OpenID Connect scopes.", nameof(authorit |
| | | 1365 | | } |
| | | 1366 | | |
| | 0 | 1367 | | var metadataAddress = authority.TrimEnd('/') + "/.well-known/openid-configuration"; |
| | | 1368 | | |
| | 0 | 1369 | | var documentRetriever = new HttpDocumentRetriever |
| | 0 | 1370 | | { |
| | 0 | 1371 | | RequireHttps = metadataAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1372 | | }; |
| | | 1373 | | |
| | 0 | 1374 | | var configManager = new ConfigurationManager<OpenIdConnectConfiguration>( |
| | 0 | 1375 | | metadataAddress, |
| | 0 | 1376 | | new OpenIdConnectConfigurationRetriever(), |
| | 0 | 1377 | | documentRetriever); |
| | | 1378 | | |
| | | 1379 | | try |
| | | 1380 | | { |
| | 0 | 1381 | | var cfg = configManager.GetConfigurationAsync(CancellationToken.None) |
| | 0 | 1382 | | .GetAwaiter() |
| | 0 | 1383 | | .GetResult(); |
| | | 1384 | | // First try the strongly-typed property |
| | 0 | 1385 | | var scopes = cfg.ScopesSupported; |
| | | 1386 | | |
| | | 1387 | | // If it's null or empty, fall back to raw JSON |
| | 0 | 1388 | | if (scopes == null || scopes.Count == 0) |
| | | 1389 | | { |
| | 0 | 1390 | | var json = documentRetriever.GetDocumentAsync(metadataAddress, CancellationToken.None) |
| | 0 | 1391 | | .GetAwaiter() |
| | 0 | 1392 | | .GetResult(); |
| | | 1393 | | |
| | 0 | 1394 | | using var doc = JsonDocument.Parse(json); |
| | 0 | 1395 | | if (doc.RootElement.TryGetProperty("scopes_supported", out var scopesElement) && |
| | 0 | 1396 | | scopesElement.ValueKind == JsonValueKind.Array) |
| | | 1397 | | { |
| | 0 | 1398 | | foreach (var scope in scopesElement.EnumerateArray().Select(item => item.GetString()).Where(s => !st |
| | | 1399 | | { |
| | 0 | 1400 | | if (scope != null) |
| | | 1401 | | { |
| | 0 | 1402 | | _ = claimPolicy.AddPolicy(policyName: scope, claimType: "scope", description: string.Empty, |
| | | 1403 | | } |
| | | 1404 | | } |
| | | 1405 | | } |
| | | 1406 | | } |
| | | 1407 | | else |
| | | 1408 | | { |
| | | 1409 | | // Normal path: configuration object had scopes |
| | 0 | 1410 | | foreach (var scope in scopes) |
| | | 1411 | | { |
| | 0 | 1412 | | _ = claimPolicy.AddPolicy(policyName: scope, claimType: "scope", description: string.Empty, allowedV |
| | | 1413 | | } |
| | | 1414 | | } |
| | 0 | 1415 | | return claimPolicy.Build(); |
| | | 1416 | | } |
| | 0 | 1417 | | catch (Exception ex) |
| | | 1418 | | { |
| | 0 | 1419 | | logger.Warning(ex, "Failed to retrieve OpenID Connect configuration from {MetadataAddress}", metadataAddress |
| | 0 | 1420 | | return null; |
| | | 1421 | | } |
| | 0 | 1422 | | } |
| | | 1423 | | |
| | | 1424 | | #endregion |
| | | 1425 | | #region Helper Methods |
| | | 1426 | | /// <summary> |
| | | 1427 | | /// Configures OpenAPI security schemes for the given authentication options. |
| | | 1428 | | /// </summary> |
| | | 1429 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1430 | | /// <param name="scheme">The authentication scheme name.</param> |
| | | 1431 | | /// <param name="opts">The OpenAPI authentication options.</param> |
| | | 1432 | | private static void ConfigureOpenApi(KestrunHost host, string scheme, IOpenApiAuthenticationOptions opts) |
| | | 1433 | | { |
| | | 1434 | | // Apply to specified documentation IDs or all if none specified |
| | 21 | 1435 | | if (opts.DocumentationId == null || opts.DocumentationId.Length == 0) |
| | | 1436 | | { |
| | 21 | 1437 | | opts.DocumentationId = OpenApiDocDescriptor.DefaultDocumentationIds; |
| | | 1438 | | } |
| | | 1439 | | |
| | 84 | 1440 | | foreach (var docDescriptor in opts.DocumentationId |
| | 21 | 1441 | | .Select(host.GetOrCreateOpenApiDocument) |
| | 42 | 1442 | | .Where(docDescriptor => docDescriptor != null)) |
| | | 1443 | | { |
| | 21 | 1444 | | docDescriptor.ApplySecurityScheme(scheme, opts); |
| | | 1445 | | } |
| | 21 | 1446 | | } |
| | | 1447 | | |
| | | 1448 | | #endregion |
| | | 1449 | | |
| | | 1450 | | /// <summary> |
| | | 1451 | | /// Adds authentication and authorization middleware to the Kestrun host. |
| | | 1452 | | /// </summary> |
| | | 1453 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1454 | | /// <param name="buildSchemes">A delegate to configure authentication schemes.</param> |
| | | 1455 | | /// <param name="defaultScheme">The default authentication scheme.</param> |
| | | 1456 | | /// <param name="configureAuthz">Optional authorization policy configuration.</param> |
| | | 1457 | | /// <param name="defaultChallengeScheme">The default challenge scheme .</param> |
| | | 1458 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 1459 | | internal static KestrunHost AddAuthentication( |
| | | 1460 | | this KestrunHost host, |
| | | 1461 | | string defaultScheme, |
| | | 1462 | | Action<AuthenticationBuilder>? buildSchemes = null, // e.g., ab => ab.AddCookie().AddOpenIdConnect("oidc", ...) |
| | | 1463 | | Action<AuthorizationOptions>? configureAuthz = null, |
| | | 1464 | | string? defaultChallengeScheme = null) |
| | | 1465 | | { |
| | 21 | 1466 | | ArgumentNullException.ThrowIfNull(buildSchemes); |
| | 21 | 1467 | | if (string.IsNullOrWhiteSpace(defaultScheme)) |
| | | 1468 | | { |
| | 0 | 1469 | | throw new ArgumentException("Default scheme is required.", nameof(defaultScheme)); |
| | | 1470 | | } |
| | | 1471 | | |
| | 21 | 1472 | | _ = host.AddService(services => |
| | 21 | 1473 | | { |
| | 21 | 1474 | | // CRITICAL: Check if authentication services are already registered |
| | 21 | 1475 | | // If they are, we only need to add new schemes, not reconfigure defaults |
| | 2418 | 1476 | | var authDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(IAuthenticationService)); |
| | 21 | 1477 | | |
| | 21 | 1478 | | AuthenticationBuilder authBuilder; |
| | 21 | 1479 | | if (authDescriptor != null) |
| | 21 | 1480 | | { |
| | 21 | 1481 | | // Authentication already registered - only add new schemes without changing defaults |
| | 0 | 1482 | | host.Logger.Debug("Authentication services already registered - adding schemes only (default={DefaultSch |
| | 0 | 1483 | | authBuilder = new AuthenticationBuilder(services); |
| | 21 | 1484 | | } |
| | 21 | 1485 | | else |
| | 21 | 1486 | | { |
| | 21 | 1487 | | // First time registration - configure defaults |
| | 21 | 1488 | | host.Logger.Debug( |
| | 21 | 1489 | | "Registering authentication services with defaults (default={DefaultScheme}, challenge={ChallengeSch |
| | 21 | 1490 | | defaultScheme, |
| | 21 | 1491 | | defaultChallengeScheme ?? defaultScheme); |
| | 21 | 1492 | | authBuilder = services.AddAuthentication(options => |
| | 21 | 1493 | | { |
| | 14 | 1494 | | options.DefaultScheme = defaultScheme; |
| | 14 | 1495 | | options.DefaultChallengeScheme = defaultChallengeScheme ?? defaultScheme; |
| | 35 | 1496 | | }); |
| | 21 | 1497 | | } |
| | 21 | 1498 | | |
| | 21 | 1499 | | // Let caller add handlers/schemes |
| | 21 | 1500 | | buildSchemes?.Invoke(authBuilder); |
| | 21 | 1501 | | |
| | 21 | 1502 | | // Ensure Authorization is available (with optional customization) |
| | 21 | 1503 | | // AddAuthorization is idempotent - safe to call multiple times |
| | 21 | 1504 | | _ = configureAuthz is not null ? |
| | 21 | 1505 | | services.AddAuthorization(configureAuthz) : |
| | 21 | 1506 | | services.AddAuthorization(); |
| | 24 | 1507 | | }); |
| | | 1508 | | |
| | | 1509 | | // Add middleware once |
| | 21 | 1510 | | return host.Use(app => |
| | 21 | 1511 | | { |
| | 21 | 1512 | | const string Key = "__kr.authmw"; |
| | 21 | 1513 | | if (!app.Properties.ContainsKey(Key)) |
| | 21 | 1514 | | { |
| | 21 | 1515 | | _ = app.UseAuthentication(); |
| | 21 | 1516 | | _ = app.UseAuthorization(); |
| | 21 | 1517 | | app.Properties[Key] = true; |
| | 21 | 1518 | | host.Logger.Information("Kestrun: Authentication & Authorization middleware added."); |
| | 21 | 1519 | | } |
| | 42 | 1520 | | }); |
| | | 1521 | | } |
| | | 1522 | | |
| | | 1523 | | /// <summary> |
| | | 1524 | | /// Checks if the specified authentication scheme is registered in the Kestrun host. |
| | | 1525 | | /// </summary> |
| | | 1526 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1527 | | /// <param name="schemeName">The name of the authentication scheme to check.</param> |
| | | 1528 | | /// <returns>True if the scheme is registered; otherwise, false.</returns> |
| | | 1529 | | public static bool HasAuthScheme(this KestrunHost host, string schemeName) |
| | | 1530 | | { |
| | 14 | 1531 | | var schemeProvider = host.App.Services.GetRequiredService<IAuthenticationSchemeProvider>(); |
| | 14 | 1532 | | var scheme = schemeProvider.GetSchemeAsync(schemeName).GetAwaiter().GetResult(); |
| | 14 | 1533 | | return scheme != null; |
| | | 1534 | | } |
| | | 1535 | | |
| | | 1536 | | /// <summary> |
| | | 1537 | | /// Adds authorization services to the Kestrun host. |
| | | 1538 | | /// </summary> |
| | | 1539 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1540 | | /// <param name="cfg">Optional configuration for authorization options.</param> |
| | | 1541 | | /// <returns>The configured KestrunHost instance.</returns> |
| | | 1542 | | public static KestrunHost AddAuthorization(this KestrunHost host, Action<AuthorizationOptions>? cfg = null) |
| | | 1543 | | { |
| | 1 | 1544 | | return host.AddService(services => |
| | 1 | 1545 | | { |
| | 1 | 1546 | | _ = cfg == null ? services.AddAuthorization() : services.AddAuthorization(cfg); |
| | 2 | 1547 | | }); |
| | | 1548 | | } |
| | | 1549 | | |
| | | 1550 | | /// <summary> |
| | | 1551 | | /// Checks if the specified authorization policy is registered in the Kestrun host. |
| | | 1552 | | /// </summary> |
| | | 1553 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 1554 | | /// <param name="policyName">The name of the authorization policy to check.</param> |
| | | 1555 | | /// <returns>True if the policy is registered; otherwise, false.</returns> |
| | | 1556 | | public static bool HasAuthPolicy(this KestrunHost host, string policyName) |
| | | 1557 | | { |
| | 13 | 1558 | | var policyProvider = host.App.Services.GetRequiredService<IAuthorizationPolicyProvider>(); |
| | 13 | 1559 | | var policy = policyProvider.GetPolicyAsync(policyName).GetAwaiter().GetResult(); |
| | 13 | 1560 | | return policy != null; |
| | | 1561 | | } |
| | | 1562 | | |
| | | 1563 | | /// <summary> |
| | | 1564 | | /// HTTP message handler that logs all HTTP requests and responses for debugging. |
| | | 1565 | | /// </summary> |
| | 0 | 1566 | | internal class LoggingHttpMessageHandler(HttpMessageHandler innerHandler, Serilog.ILogger logger) : DelegatingHandle |
| | | 1567 | | { |
| | 0 | 1568 | | private readonly Serilog.ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | | 1569 | | |
| | | 1570 | | // CRITICAL: Static field to store the last token response body so we can manually parse it |
| | | 1571 | | // The framework's OpenIdConnectMessage parser fails to populate AccessToken correctly |
| | 0 | 1572 | | internal static string? LastTokenResponseBody { get; private set; } |
| | | 1573 | | |
| | | 1574 | | protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cance |
| | | 1575 | | { |
| | | 1576 | | // Log request |
| | 0 | 1577 | | _logger.Warning($"HTTP {request.Method} {request.RequestUri}"); |
| | | 1578 | | |
| | | 1579 | | // Check if this is a token endpoint request |
| | 0 | 1580 | | var isTokenEndpoint = request.RequestUri?.PathAndQuery?.Contains("/connect/token") == true || |
| | 0 | 1581 | | request.RequestUri?.PathAndQuery?.Contains("/token") == true; |
| | | 1582 | | |
| | 0 | 1583 | | if (request.Content != null && !isTokenEndpoint) |
| | | 1584 | | { |
| | | 1585 | | // Read request body without consuming it (only for non-token requests) |
| | 0 | 1586 | | var requestBytes = await request.Content.ReadAsByteArrayAsync(cancellationToken); |
| | 0 | 1587 | | var requestBody = System.Text.Encoding.UTF8.GetString(requestBytes); |
| | 0 | 1588 | | _logger.Warning($"Request Body: {requestBody}"); |
| | | 1589 | | |
| | | 1590 | | // Recreate the content so it can be read again |
| | 0 | 1591 | | request.Content = new ByteArrayContent(requestBytes); |
| | 0 | 1592 | | request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-ww |
| | | 1593 | | } |
| | 0 | 1594 | | else if (request.Content != null && isTokenEndpoint) |
| | | 1595 | | { |
| | 0 | 1596 | | _logger.Warning("Token endpoint request - skipping body logging to preserve stream"); |
| | | 1597 | | } |
| | | 1598 | | |
| | | 1599 | | // Send request |
| | 0 | 1600 | | var response = await base.SendAsync(request, cancellationToken); |
| | | 1601 | | |
| | | 1602 | | // Log response |
| | 0 | 1603 | | _logger.Warning($"HTTP Response: {(int)response.StatusCode} {response.StatusCode}"); |
| | | 1604 | | |
| | | 1605 | | // CRITICAL: For token endpoint responses, capture the body for manual parsing |
| | | 1606 | | // but then recreate the stream so the framework can also read it |
| | 0 | 1607 | | if (response.Content != null && isTokenEndpoint) |
| | | 1608 | | { |
| | | 1609 | | // Read the response body |
| | 0 | 1610 | | var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken); |
| | 0 | 1611 | | var responseBody = System.Text.Encoding.UTF8.GetString(responseBytes); |
| | | 1612 | | |
| | | 1613 | | // Store it in static field for later manual parsing |
| | 0 | 1614 | | LastTokenResponseBody = responseBody; |
| | 0 | 1615 | | _logger.Warning($"Captured token response body ({responseBytes.Length} bytes) for manual parsing"); |
| | | 1616 | | |
| | | 1617 | | // Recreate the content stream with ALL original headers preserved |
| | 0 | 1618 | | var originalHeaders = response.Content.Headers.ToList(); |
| | 0 | 1619 | | var newContent = new ByteArrayContent(responseBytes); |
| | | 1620 | | |
| | 0 | 1621 | | foreach (var header in originalHeaders) |
| | | 1622 | | { |
| | 0 | 1623 | | _ = newContent.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| | | 1624 | | } |
| | | 1625 | | |
| | 0 | 1626 | | response.Content = newContent; |
| | 0 | 1627 | | _logger.Warning("Recreated token response stream for framework parsing"); |
| | | 1628 | | } |
| | 0 | 1629 | | else if (response.Content != null && !isTokenEndpoint) |
| | | 1630 | | { |
| | | 1631 | | // Save original headers |
| | 0 | 1632 | | var originalHeaders = response.Content.Headers; |
| | | 1633 | | |
| | | 1634 | | // Read response body and preserve it for the handler |
| | 0 | 1635 | | var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken); |
| | 0 | 1636 | | var responseBody = System.Text.Encoding.UTF8.GetString(responseBytes); |
| | 0 | 1637 | | _logger.Warning($"Response Body: {responseBody}"); |
| | | 1638 | | |
| | | 1639 | | // Recreate the content so it can be read again by the OIDC handler |
| | 0 | 1640 | | var newContent = new ByteArrayContent(responseBytes); |
| | | 1641 | | |
| | | 1642 | | // Copy all original headers to the new content |
| | 0 | 1643 | | foreach (var header in originalHeaders) |
| | | 1644 | | { |
| | 0 | 1645 | | _ = newContent.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| | | 1646 | | } |
| | | 1647 | | |
| | 0 | 1648 | | response.Content = newContent; |
| | 0 | 1649 | | } |
| | 0 | 1650 | | else if (response.Content != null && isTokenEndpoint) |
| | | 1651 | | { |
| | 0 | 1652 | | _logger.Warning("Token endpoint response - skipping body logging to let framework parse it"); |
| | | 1653 | | } |
| | | 1654 | | |
| | 0 | 1655 | | return response; |
| | 0 | 1656 | | } |
| | | 1657 | | } |
| | | 1658 | | } |