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