| | 1 | | using Microsoft.AspNetCore.Authentication; |
| | 2 | | using Microsoft.AspNetCore.Authentication.Cookies; |
| | 3 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 4 | | using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| | 5 | | using Microsoft.IdentityModel.Tokens; |
| | 6 | | using Microsoft.AspNetCore.Authorization; |
| | 7 | | using Microsoft.Extensions.Options; |
| | 8 | | using System.Text.RegularExpressions; |
| | 9 | | using Kestrun.Authentication; |
| | 10 | | using Serilog.Events; |
| | 11 | | using Kestrun.Scripting; |
| | 12 | | using Microsoft.AspNetCore.Authentication.Negotiate; |
| | 13 | | using Kestrun.Claims; |
| | 14 | | using Serilog; |
| | 15 | |
|
| | 16 | |
|
| | 17 | | namespace Kestrun.Hosting; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Provides extension methods for adding authentication and authorization schemes to the Kestrun host. |
| | 21 | | /// </summary> |
| | 22 | | public static class KestrunHostAuthExtensions |
| | 23 | | { |
| | 24 | | /// <summary> |
| | 25 | | /// Adds Basic Authentication to the Kestrun host. |
| | 26 | | /// <para>Use this for simple username/password authentication.</para> |
| | 27 | | /// </summary> |
| | 28 | | /// <param name="host">The Kestrun host instance.</param> |
| | 29 | | /// <param name="scheme">The authentication scheme name (e.g. "Basic").</param> |
| | 30 | | /// <param name="configure">Optional configuration for BasicAuthenticationOptions.</param> |
| | 31 | | /// <returns>returns the KestrunHost instance.</returns> |
| | 32 | | public static KestrunHost AddBasicAuthentication( |
| | 33 | | this KestrunHost host, |
| | 34 | | string scheme = "Basic", |
| | 35 | | Action<BasicAuthenticationOptions>? configure = null |
| | 36 | | ) |
| | 37 | | { |
| 8 | 38 | | var h = host.AddAuthentication( |
| 8 | 39 | | defaultScheme: scheme, |
| 8 | 40 | | buildSchemes: ab => |
| 8 | 41 | | { |
| 8 | 42 | | // ← TOptions == BasicAuthenticationOptions |
| 8 | 43 | | // THandler == BasicAuthHandler |
| 8 | 44 | | _ = ab.AddScheme<BasicAuthenticationOptions, BasicAuthHandler>( |
| 8 | 45 | | authenticationScheme: scheme, |
| 8 | 46 | | displayName: "Basic Authentication", |
| 8 | 47 | | configureOptions: opts => |
| 8 | 48 | | { |
| 8 | 49 | | // let caller mutate everything first |
| 6 | 50 | | configure?.Invoke(opts); |
| 6 | 51 | | ConfigureBasicAuthValidators(opts); |
| 6 | 52 | | ConfigureBasicIssueClaims(opts); |
| 14 | 53 | | }); |
| 8 | 54 | | } |
| 8 | 55 | | ); |
| | 56 | | // register the post-configurer **after** the scheme so it can |
| | 57 | | // read BasicAuthenticationOptions for <scheme> |
| 8 | 58 | | return h.AddService(services => |
| 8 | 59 | | { |
| 8 | 60 | | _ = services.AddSingleton<IPostConfigureOptions<AuthorizationOptions>>( |
| 11 | 61 | | sp => new ClaimPolicyPostConfigurer( |
| 11 | 62 | | scheme, |
| 11 | 63 | | sp.GetRequiredService< |
| 11 | 64 | | IOptionsMonitor<BasicAuthenticationOptions>>())); |
| 16 | 65 | | }); |
| | 66 | | } |
| | 67 | | /// <summary> |
| | 68 | | /// Adds Basic Authentication to the Kestrun host using the provided options object. |
| | 69 | | /// </summary> |
| | 70 | | /// <param name="host">The Kestrun host instance.</param> |
| | 71 | | /// <param name="scheme">The authentication scheme name (e.g. "Basic").</param> |
| | 72 | | /// <param name="configure">The BasicAuthenticationOptions object to configure the authentication.</param> |
| | 73 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 74 | | public static KestrunHost AddBasicAuthentication( |
| | 75 | | this KestrunHost host, |
| | 76 | | string scheme, |
| | 77 | | BasicAuthenticationOptions configure |
| | 78 | | ) |
| | 79 | | { |
| 1 | 80 | | if (host.HostLogger.IsEnabled(LogEventLevel.Debug)) |
| | 81 | | { |
| 1 | 82 | | host.HostLogger.Debug("Adding Basic Authentication with scheme: {Scheme}", scheme); |
| | 83 | | } |
| | 84 | | // Ensure the scheme is not null |
| 1 | 85 | | ArgumentNullException.ThrowIfNull(host); |
| 1 | 86 | | ArgumentNullException.ThrowIfNull(scheme); |
| 1 | 87 | | ArgumentNullException.ThrowIfNull(configure); |
| 1 | 88 | | return host.AddBasicAuthentication( |
| 1 | 89 | | scheme: scheme, |
| 1 | 90 | | configure: opts => |
| 1 | 91 | | { |
| 1 | 92 | | // Copy properties from the provided configure object |
| 1 | 93 | | opts.HeaderName = configure.HeaderName; |
| 1 | 94 | | opts.Base64Encoded = configure.Base64Encoded; |
| 1 | 95 | | if (configure.SeparatorRegex is not null) |
| 1 | 96 | | { |
| 1 | 97 | | opts.SeparatorRegex = new Regex(configure.SeparatorRegex.ToString(), configure.SeparatorRegex.Option |
| 1 | 98 | | } |
| 1 | 99 | |
|
| 1 | 100 | | opts.Realm = configure.Realm; |
| 1 | 101 | | opts.RequireHttps = configure.RequireHttps; |
| 1 | 102 | | opts.SuppressWwwAuthenticate = configure.SuppressWwwAuthenticate; |
| 1 | 103 | | // Logger configuration |
| 1 | 104 | | opts.Logger = configure.Logger == Log.ForContext<BasicAuthenticationOptions>() ? |
| 1 | 105 | | host.HostLogger.ForContext<BasicAuthenticationOptions>() : configure.Logger; |
| 1 | 106 | |
|
| 1 | 107 | | // Copy properties from the provided configure object |
| 1 | 108 | | opts.ValidateCodeSettings = configure.ValidateCodeSettings; |
| 1 | 109 | | opts.IssueClaimsCodeSettings = configure.IssueClaimsCodeSettings; |
| 1 | 110 | |
|
| 1 | 111 | | // Claims policy configuration |
| 1 | 112 | | opts.ClaimPolicyConfig = configure.ClaimPolicyConfig; |
| 1 | 113 | | } |
| 1 | 114 | | ); |
| | 115 | | } |
| | 116 | |
|
| | 117 | |
|
| | 118 | | /// <summary> |
| | 119 | | /// Adds JWT Bearer authentication to the Kestrun host. |
| | 120 | | /// <para>Use this for APIs that require token-based authentication.</para> |
| | 121 | | /// </summary> |
| | 122 | | /// <param name="host">The Kestrun host instance.</param> |
| | 123 | | /// <param name="scheme">The authentication scheme name (e.g. "Bearer").</param> |
| | 124 | | /// <param name="validationParameters">Parameters used to validate JWT tokens.</param> |
| | 125 | | /// <param name="configureJwt">Optional hook to customize JwtBearerOptions.</param> |
| | 126 | | /// <param name="claimPolicy">Optional authorization policy configuration.</param> |
| | 127 | | /// <example> |
| | 128 | | /// HS512 (HMAC-SHA-512, symmetric) |
| | 129 | | /// </example> |
| | 130 | | /// <code> |
| | 131 | | /// var hmacKey = new SymmetricSecurityKey( |
| | 132 | | /// Encoding.UTF8.GetBytes("32-bytes-or-more-secret……")); |
| | 133 | | /// host.AddJwtBearerAuthentication( |
| | 134 | | /// scheme: "Bearer", |
| | 135 | | /// issuer: "KestrunApi", |
| | 136 | | /// audience: "KestrunClients", |
| | 137 | | /// validationKey: hmacKey, |
| | 138 | | /// validAlgorithms: new[] { SecurityAlgorithms.HmacSha512 }); |
| | 139 | | /// </code> |
| | 140 | | /// <example> |
| | 141 | | /// RS256 (RSA-SHA-256, asymmetric) |
| | 142 | | /// <para>Requires a PEM-encoded private key file.</para> |
| | 143 | | /// <code> |
| | 144 | | /// using var rsa = RSA.Create(); |
| | 145 | | /// rsa.ImportFromPem(File.ReadAllText("private-key.pem")); |
| | 146 | | /// var rsaKey = new RsaSecurityKey(rsa); |
| | 147 | | /// |
| | 148 | | /// host.AddJwtBearerAuthentication( |
| | 149 | | /// scheme: "Rs256", |
| | 150 | | /// issuer: "KestrunApi", |
| | 151 | | /// audience: "KestrunClients", |
| | 152 | | /// validationKey: rsaKey, |
| | 153 | | /// validAlgorithms: new[] { SecurityAlgorithms.RsaSha256 }); |
| | 154 | | /// </code> |
| | 155 | | /// </example> |
| | 156 | | /// <example> |
| | 157 | | /// ES256 (ECDSA-SHA-256, asymmetric) |
| | 158 | | /// <para>Requires a PEM-encoded private key file.</para> |
| | 159 | | /// <code> |
| | 160 | | /// using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); |
| | 161 | | /// var esKey = new ECDsaSecurityKey(ecdsa); |
| | 162 | | /// host.AddJwtBearerAuthentication( |
| | 163 | | /// "Es256", "KestrunApi", "KestrunClients", |
| | 164 | | /// esKey, new[] { SecurityAlgorithms.EcdsaSha256 }); |
| | 165 | | /// </code> |
| | 166 | | /// </example> |
| | 167 | | /// <returns></returns> |
| | 168 | | public static KestrunHost AddJwtBearerAuthentication( |
| | 169 | | this KestrunHost host, |
| | 170 | | string scheme, |
| | 171 | | TokenValidationParameters validationParameters, |
| | 172 | | Action<JwtBearerOptions>? configureJwt = null, |
| | 173 | | ClaimPolicyConfig? claimPolicy = null) |
| | 174 | | { |
| 3 | 175 | | return host.AddAuthentication( |
| 3 | 176 | | defaultScheme: scheme, |
| 3 | 177 | | buildSchemes: ab => |
| 3 | 178 | | { |
| 3 | 179 | | _ = ab.AddJwtBearer(scheme, opts => |
| 3 | 180 | | { |
| 0 | 181 | | opts.TokenValidationParameters = validationParameters; |
| 0 | 182 | | opts.MapInboundClaims = true; |
| 0 | 183 | | configureJwt?.Invoke(opts); |
| 3 | 184 | | }); |
| 3 | 185 | | }, |
| 3 | 186 | | configureAuthz: claimPolicy?.ToAuthzDelegate() |
| 3 | 187 | | ); |
| | 188 | | } |
| | 189 | |
|
| | 190 | | /// <summary> |
| | 191 | | /// Adds Cookie Authentication to the Kestrun host. |
| | 192 | | /// <para>Use this for browser-based authentication using cookies.</para> |
| | 193 | | /// </summary> |
| | 194 | | /// <param name="host">The Kestrun host instance.</param> |
| | 195 | | /// <param name="scheme">The authentication scheme name (default is CookieAuthenticationDefaults.AuthenticationSchem |
| | 196 | | /// <param name="configure">Optional configuration for CookieAuthenticationOptions.</param> |
| | 197 | | /// <param name="claimPolicy">Optional authorization policy configuration.</param> |
| | 198 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 199 | | public static KestrunHost AddCookieAuthentication( |
| | 200 | | this KestrunHost host, |
| | 201 | | string scheme = CookieAuthenticationDefaults.AuthenticationScheme, |
| | 202 | | Action<CookieAuthenticationOptions>? configure = null, |
| | 203 | | ClaimPolicyConfig? claimPolicy = null) |
| | 204 | | { |
| 2 | 205 | | return host.AddAuthentication( |
| 2 | 206 | | defaultScheme: scheme, |
| 2 | 207 | | buildSchemes: ab => |
| 2 | 208 | | { |
| 2 | 209 | | _ = ab.AddCookie( |
| 2 | 210 | | authenticationScheme: scheme, |
| 2 | 211 | | configureOptions: opts => |
| 2 | 212 | | { |
| 2 | 213 | | // let caller mutate everything first |
| 0 | 214 | | configure?.Invoke(opts); |
| 0 | 215 | | Log.Debug("Configured Cookie Authentication with LoginPath: {LoginPath}", opts.LoginPath); |
| 2 | 216 | | }); |
| 2 | 217 | | }, |
| 2 | 218 | | configureAuthz: claimPolicy?.ToAuthzDelegate() |
| 2 | 219 | | ); |
| | 220 | | } |
| | 221 | |
|
| | 222 | |
|
| | 223 | | /// <summary> |
| | 224 | | /// Adds Cookie Authentication to the Kestrun host using the provided options object. |
| | 225 | | /// </summary> |
| | 226 | | /// <param name="host">The Kestrun host instance.</param> |
| | 227 | | /// <param name="scheme">The authentication scheme name (default is CookieAuthenticationDefaults.AuthenticationSchem |
| | 228 | | /// <param name="configure">The CookieAuthenticationOptions object to configure the authentication.</param> |
| | 229 | | /// <param name="claimPolicy">Optional authorization policy configuration.</param> |
| | 230 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 231 | | public static KestrunHost AddCookieAuthentication( |
| | 232 | | this KestrunHost host, |
| | 233 | | string scheme = CookieAuthenticationDefaults.AuthenticationScheme, |
| | 234 | | CookieAuthenticationOptions? configure = null, |
| | 235 | | ClaimPolicyConfig? claimPolicy = null) |
| | 236 | | { |
| | 237 | | // If no object provided just delegate to action overload without extra config |
| 0 | 238 | | return configure is null |
| 0 | 239 | | ? host.AddCookieAuthentication( |
| 0 | 240 | | scheme: scheme, |
| 0 | 241 | | configure: (Action<CookieAuthenticationOptions>?)null, |
| 0 | 242 | | claimPolicy: claimPolicy) |
| 0 | 243 | | : host.AddCookieAuthentication( |
| 0 | 244 | | scheme: scheme, |
| 0 | 245 | | configure: opts => |
| 0 | 246 | | { |
| 0 | 247 | | // Copy relevant properties from provided options instance to the framework-created one |
| 0 | 248 | | CopyCookieAuthenticationOptions(configure, opts); |
| 0 | 249 | | }, |
| 0 | 250 | | claimPolicy: claimPolicy |
| 0 | 251 | | ); |
| | 252 | | } |
| | 253 | |
|
| | 254 | |
|
| | 255 | | /* |
| | 256 | | public static KestrunHost AddClientCertificateAuthentication( |
| | 257 | | this KestrunHost host, |
| | 258 | | string scheme = CertificateAuthenticationDefaults.AuthenticationScheme, |
| | 259 | | Action<CertificateAuthenticationOptions>? configure = null, |
| | 260 | | Action<AuthorizationOptions>? configureAuthz = null) |
| | 261 | | { |
| | 262 | | return host.AddAuthentication( |
| | 263 | | defaultScheme: scheme, |
| | 264 | | buildSchemes: ab => |
| | 265 | | { |
| | 266 | | ab.AddCertificate( |
| | 267 | | authenticationScheme: scheme, |
| | 268 | | configureOptions: configure ?? (opts => { })); |
| | 269 | | }, |
| | 270 | | configureAuthz: configureAuthz |
| | 271 | | ); |
| | 272 | | } |
| | 273 | | */ |
| | 274 | | /// <summary> |
| | 275 | | /// Adds Windows Authentication to the Kestrun host. |
| | 276 | | /// <para> |
| | 277 | | /// The authentication scheme name is <see cref="NegotiateDefaults.AuthenticationScheme"/>. |
| | 278 | | /// This enables Kerberos and NTLM authentication. |
| | 279 | | /// </para> |
| | 280 | | /// </summary> |
| | 281 | | /// <param name="host">The Kestrun host instance.</param> |
| | 282 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 283 | | public static KestrunHost AddWindowsAuthentication(this KestrunHost host) |
| | 284 | | { |
| 1 | 285 | | return host.AddAuthentication( |
| 1 | 286 | | defaultScheme: NegotiateDefaults.AuthenticationScheme, |
| 1 | 287 | | buildSchemes: ab => |
| 1 | 288 | | { |
| 1 | 289 | | _ = ab.AddNegotiate(); |
| 1 | 290 | | } |
| 1 | 291 | | ); |
| | 292 | | } |
| | 293 | | /// <summary> |
| | 294 | | /// Adds API Key Authentication to the Kestrun host. |
| | 295 | | /// <para>Use this for endpoints that require an API key for access.</para> |
| | 296 | | /// </summary> |
| | 297 | | /// <param name="host">The Kestrun host instance.</param> |
| | 298 | | /// <param name="scheme">The authentication scheme name (default is "ApiKey").</param> |
| | 299 | | /// <param name="configure">Optional configuration for ApiKeyAuthenticationOptions.</param> |
| | 300 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 301 | | public static KestrunHost AddApiKeyAuthentication( |
| | 302 | | this KestrunHost host, |
| | 303 | | string scheme = "ApiKey", |
| | 304 | | Action<ApiKeyAuthenticationOptions>? configure = null) |
| | 305 | | { |
| 6 | 306 | | var h = host.AddAuthentication( |
| 6 | 307 | | defaultScheme: scheme, |
| 6 | 308 | | buildSchemes: ab => |
| 6 | 309 | | { |
| 6 | 310 | | // ← TOptions == ApiKeyAuthenticationOptions |
| 6 | 311 | | // THandler == ApiKeyAuthHandler |
| 6 | 312 | | _ = ab.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthHandler>( |
| 6 | 313 | | authenticationScheme: scheme, |
| 6 | 314 | | displayName: "API Key", |
| 6 | 315 | | configureOptions: opts => |
| 6 | 316 | | { |
| 6 | 317 | | // let caller mutate everything first |
| 6 | 318 | | configure?.Invoke(opts); |
| 6 | 319 | | ConfigureApiKeyValidators(opts); |
| 6 | 320 | | ConfigureApiKeyIssueClaims(opts); |
| 12 | 321 | | }); |
| 6 | 322 | | } |
| 6 | 323 | | ); |
| | 324 | | // register the post-configurer **after** the scheme so it can |
| | 325 | | // read BasicAuthenticationOptions for <scheme> |
| 6 | 326 | | return h.AddService(services => |
| 6 | 327 | | { |
| 6 | 328 | | _ = services.AddSingleton<IPostConfigureOptions<AuthorizationOptions>>( |
| 9 | 329 | | sp => new ClaimPolicyPostConfigurer( |
| 9 | 330 | | scheme, |
| 9 | 331 | | sp.GetRequiredService< |
| 9 | 332 | | IOptionsMonitor<ApiKeyAuthenticationOptions>>())); |
| 12 | 333 | | }); |
| | 334 | | } |
| | 335 | |
|
| | 336 | | /// <summary> |
| | 337 | | /// Configures the validators for Basic authentication. |
| | 338 | | /// </summary> |
| | 339 | | /// <param name="opts">The options to configure.</param> |
| | 340 | | private static void ConfigureBasicAuthValidators(BasicAuthenticationOptions opts) |
| | 341 | | { |
| 6 | 342 | | var settings = opts.ValidateCodeSettings; |
| 6 | 343 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | 344 | | { |
| 3 | 345 | | return; |
| | 346 | | } |
| | 347 | |
|
| 3 | 348 | | switch (settings.Language) |
| | 349 | | { |
| | 350 | | case ScriptLanguage.PowerShell: |
| 1 | 351 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 352 | | { |
| 1 | 353 | | opts.Logger.Debug("Building PowerShell validator for Basic authentication"); |
| | 354 | | } |
| | 355 | |
|
| 1 | 356 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildPsValidator(settings, opts.Logger); |
| 1 | 357 | | break; |
| | 358 | | case ScriptLanguage.CSharp: |
| 1 | 359 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 360 | | { |
| 1 | 361 | | opts.Logger.Debug("Building C# validator for Basic authentication"); |
| | 362 | | } |
| | 363 | |
|
| 1 | 364 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildCsValidator(settings, opts.Logger); |
| 1 | 365 | | break; |
| | 366 | | case ScriptLanguage.VBNet: |
| 1 | 367 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 368 | | { |
| 1 | 369 | | opts.Logger.Debug("Building VB.NET validator for Basic authentication"); |
| | 370 | | } |
| | 371 | |
|
| 1 | 372 | | opts.ValidateCredentialsAsync = BasicAuthHandler.BuildVBNetValidator(settings, opts.Logger); |
| 1 | 373 | | break; |
| | 374 | | default: |
| 0 | 375 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | 376 | | { |
| 0 | 377 | | opts.Logger.Warning("No valid language specified for Basic authentication"); |
| | 378 | | } |
| | 379 | | break; |
| | 380 | | } |
| 0 | 381 | | } |
| | 382 | |
|
| | 383 | | /// <summary> |
| | 384 | | /// Configures the issue claims for Basic authentication. |
| | 385 | | /// </summary> |
| | 386 | | /// <param name="opts">The options to configure.</param> |
| | 387 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | 388 | | private static void ConfigureBasicIssueClaims(BasicAuthenticationOptions opts) |
| | 389 | | { |
| 6 | 390 | | var settings = opts.IssueClaimsCodeSettings; |
| 6 | 391 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | 392 | | { |
| 3 | 393 | | return; |
| | 394 | | } |
| | 395 | |
|
| 3 | 396 | | switch (settings.Language) |
| | 397 | | { |
| | 398 | | case ScriptLanguage.PowerShell: |
| 1 | 399 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 400 | | { |
| 1 | 401 | | opts.Logger.Debug("Building PowerShell Issue Claims for API Basic authentication"); |
| | 402 | | } |
| | 403 | |
|
| 1 | 404 | | opts.IssueClaims = IAuthHandler.BuildPsIssueClaims(settings, opts.Logger); |
| 1 | 405 | | break; |
| | 406 | | case ScriptLanguage.CSharp: |
| 1 | 407 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 408 | | { |
| 1 | 409 | | opts.Logger.Debug("Building C# Issue Claims for API Basic authentication"); |
| | 410 | | } |
| | 411 | |
|
| 1 | 412 | | opts.IssueClaims = IAuthHandler.BuildCsIssueClaims(settings, opts.Logger); |
| 1 | 413 | | break; |
| | 414 | | case ScriptLanguage.VBNet: |
| 1 | 415 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 416 | | { |
| 1 | 417 | | opts.Logger.Debug("Building VB.NET Issue Claims for API Basic authentication"); |
| | 418 | | } |
| | 419 | |
|
| 1 | 420 | | opts.IssueClaims = IAuthHandler.BuildVBNetIssueClaims(settings, opts.Logger); |
| 1 | 421 | | break; |
| | 422 | | default: |
| 0 | 423 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | 424 | | { |
| 0 | 425 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | 426 | | } |
| 0 | 427 | | throw new NotSupportedException("Unsupported language"); |
| | 428 | | } |
| | 429 | | } |
| | 430 | |
|
| | 431 | | /// <summary> |
| | 432 | | /// Configures the API Key validators. |
| | 433 | | /// </summary> |
| | 434 | | /// <param name="opts">The options to configure.</param> |
| | 435 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | 436 | | private static void ConfigureApiKeyValidators(ApiKeyAuthenticationOptions opts) |
| | 437 | | { |
| 6 | 438 | | var settings = opts.ValidateCodeSettings; |
| 6 | 439 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | 440 | | { |
| 3 | 441 | | return; |
| | 442 | | } |
| | 443 | |
|
| 3 | 444 | | switch (settings.Language) |
| | 445 | | { |
| | 446 | | case ScriptLanguage.PowerShell: |
| 1 | 447 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 448 | | { |
| 1 | 449 | | opts.Logger.Debug("Building PowerShell validator for API Key authentication"); |
| | 450 | | } |
| | 451 | |
|
| 1 | 452 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildPsValidator(settings, opts.Logger); |
| 1 | 453 | | break; |
| | 454 | | case ScriptLanguage.CSharp: |
| 1 | 455 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 456 | | { |
| 1 | 457 | | opts.Logger.Debug("Building C# validator for API Key authentication"); |
| | 458 | | } |
| | 459 | |
|
| 1 | 460 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildCsValidator(settings, opts.Logger); |
| 1 | 461 | | break; |
| | 462 | | case ScriptLanguage.VBNet: |
| 1 | 463 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 464 | | { |
| 1 | 465 | | opts.Logger.Debug("Building VB.NET validator for API Key authentication"); |
| | 466 | | } |
| | 467 | |
|
| 1 | 468 | | opts.ValidateKeyAsync = ApiKeyAuthHandler.BuildVBNetValidator(settings, opts.Logger); |
| 1 | 469 | | break; |
| | 470 | | default: |
| 0 | 471 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | 472 | | { |
| 0 | 473 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | 474 | | } |
| 0 | 475 | | throw new NotSupportedException("Unsupported language"); |
| | 476 | | } |
| | 477 | | } |
| | 478 | |
|
| | 479 | | /// <summary> |
| | 480 | | /// Configures the API Key issue claims. |
| | 481 | | /// </summary> |
| | 482 | | /// <param name="opts">The options to configure.</param> |
| | 483 | | /// <exception cref="NotSupportedException">Thrown when the language is not supported.</exception> |
| | 484 | | private static void ConfigureApiKeyIssueClaims(ApiKeyAuthenticationOptions opts) |
| | 485 | | { |
| 6 | 486 | | var settings = opts.IssueClaimsCodeSettings; |
| 6 | 487 | | if (string.IsNullOrWhiteSpace(settings.Code)) |
| | 488 | | { |
| 3 | 489 | | return; |
| | 490 | | } |
| | 491 | |
|
| 3 | 492 | | switch (settings.Language) |
| | 493 | | { |
| | 494 | | case ScriptLanguage.PowerShell: |
| 1 | 495 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 496 | | { |
| 1 | 497 | | opts.Logger.Debug("Building PowerShell Issue Claims for API Key authentication"); |
| | 498 | | } |
| | 499 | |
|
| 1 | 500 | | opts.IssueClaims = IAuthHandler.BuildPsIssueClaims(settings, opts.Logger); |
| 1 | 501 | | break; |
| | 502 | | case ScriptLanguage.CSharp: |
| 1 | 503 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 504 | | { |
| 1 | 505 | | opts.Logger.Debug("Building C# Issue Claims for API Key authentication"); |
| | 506 | | } |
| | 507 | |
|
| 1 | 508 | | opts.IssueClaims = IAuthHandler.BuildCsIssueClaims(settings, opts.Logger); |
| 1 | 509 | | break; |
| | 510 | | case ScriptLanguage.VBNet: |
| 1 | 511 | | if (opts.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 512 | | { |
| 1 | 513 | | opts.Logger.Debug("Building VB.NET Issue Claims for API Key authentication"); |
| | 514 | | } |
| | 515 | |
|
| 1 | 516 | | opts.IssueClaims = IAuthHandler.BuildVBNetIssueClaims(settings, opts.Logger); |
| 1 | 517 | | break; |
| | 518 | | default: |
| 0 | 519 | | if (opts.Logger.IsEnabled(LogEventLevel.Warning)) |
| | 520 | | { |
| 0 | 521 | | opts.Logger.Warning("{language} is not supported for API Basic authentication", settings.Language); |
| | 522 | | } |
| 0 | 523 | | throw new NotSupportedException("Unsupported language"); |
| | 524 | | } |
| | 525 | | } |
| | 526 | |
|
| | 527 | |
|
| | 528 | | /// <summary> |
| | 529 | | /// Adds API Key Authentication to the Kestrun host using the provided options object. |
| | 530 | | /// </summary> |
| | 531 | | /// <param name="host">The Kestrun host instance.</param> |
| | 532 | | /// <param name="scheme">The authentication scheme name.</param> |
| | 533 | | /// <param name="configure">The ApiKeyAuthenticationOptions object to configure the authentication.</param> |
| | 534 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 535 | | public static KestrunHost AddApiKeyAuthentication( |
| | 536 | | this KestrunHost host, |
| | 537 | | string scheme, |
| | 538 | | ApiKeyAuthenticationOptions configure) |
| | 539 | | { |
| 1 | 540 | | if (host.HostLogger.IsEnabled(LogEventLevel.Debug)) |
| | 541 | | { |
| 1 | 542 | | host.HostLogger.Debug("Adding API Key Authentication with scheme: {Scheme}", scheme); |
| | 543 | | } |
| | 544 | |
|
| 1 | 545 | | ArgumentNullException.ThrowIfNull(host); |
| 1 | 546 | | ArgumentNullException.ThrowIfNull(scheme); |
| 1 | 547 | | ArgumentNullException.ThrowIfNull(configure); |
| 1 | 548 | | return host.AddApiKeyAuthentication( |
| 1 | 549 | | scheme: scheme, |
| 1 | 550 | | configure: opts => |
| 1 | 551 | | { |
| 1 | 552 | | // let caller mutate everything first |
| 1 | 553 | | opts.ExpectedKey = configure.ExpectedKey; |
| 1 | 554 | | opts.HeaderName = configure.HeaderName; |
| 1 | 555 | | opts.AdditionalHeaderNames = configure.AdditionalHeaderNames; |
| 1 | 556 | | opts.AllowQueryStringFallback = configure.AllowQueryStringFallback; |
| 1 | 557 | | // Logger configuration |
| 1 | 558 | | opts.Logger = configure.Logger == Log.ForContext<ApiKeyAuthenticationOptions>() ? |
| 1 | 559 | | host.HostLogger.ForContext<ApiKeyAuthenticationOptions>() : configure.Logger; |
| 1 | 560 | |
|
| 1 | 561 | | opts.RequireHttps = configure.RequireHttps; |
| 1 | 562 | | opts.EmitChallengeHeader = configure.EmitChallengeHeader; |
| 1 | 563 | | opts.ChallengeHeaderFormat = configure.ChallengeHeaderFormat; |
| 1 | 564 | | opts.ValidateCodeSettings = configure.ValidateCodeSettings; |
| 1 | 565 | | // IssueClaimsCodeSettings |
| 1 | 566 | | opts.IssueClaimsCodeSettings = configure.IssueClaimsCodeSettings; |
| 1 | 567 | | // Claims policy configuration |
| 1 | 568 | | opts.ClaimPolicyConfig = configure.ClaimPolicyConfig; |
| 1 | 569 | | } |
| 1 | 570 | | ); |
| | 571 | | } |
| | 572 | |
|
| | 573 | | /// <summary> |
| | 574 | | /// Adds OpenID Connect authentication to the Kestrun host. |
| | 575 | | /// <para>Use this for applications that require OpenID Connect authentication.</para> |
| | 576 | | /// </summary> |
| | 577 | | /// <param name="host">The Kestrun host instance.</param> |
| | 578 | | /// <param name="scheme">The authentication scheme name.</param> |
| | 579 | | /// <param name="clientId">The client ID for the OpenID Connect application.</param> |
| | 580 | | /// <param name="clientSecret">The client secret for the OpenID Connect application.</param> |
| | 581 | | /// <param name="authority">The authority URL for the OpenID Connect provider.</param> |
| | 582 | | /// <param name="configure">An optional action to configure the OpenID Connect options.</param> |
| | 583 | | /// <param name="configureAuthz">An optional action to configure the authorization options.</param> |
| | 584 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 585 | | public static KestrunHost AddOpenIdConnectAuthentication( |
| | 586 | | this KestrunHost host, |
| | 587 | | string scheme, |
| | 588 | | string clientId, |
| | 589 | | string clientSecret, |
| | 590 | | string authority, |
| | 591 | | Action<OpenIdConnectOptions>? configure = null, |
| | 592 | | Action<AuthorizationOptions>? configureAuthz = null) |
| | 593 | | { |
| 2 | 594 | | return host.AddAuthentication( |
| 2 | 595 | | defaultScheme: scheme, |
| 2 | 596 | | buildSchemes: ab => |
| 2 | 597 | | { |
| 2 | 598 | | _ = ab.AddOpenIdConnect( |
| 2 | 599 | | authenticationScheme: scheme, |
| 2 | 600 | | displayName: "OIDC", |
| 2 | 601 | | configureOptions: opts => |
| 2 | 602 | | { |
| 0 | 603 | | opts.ClientId = clientId; |
| 0 | 604 | | opts.ClientSecret = clientSecret; |
| 0 | 605 | | opts.Authority = authority; |
| 0 | 606 | | opts.ResponseType = "code"; |
| 0 | 607 | | opts.SaveTokens = true; |
| 0 | 608 | | configure?.Invoke(opts); |
| 2 | 609 | | }); |
| 2 | 610 | | }, |
| 2 | 611 | | configureAuthz: configureAuthz |
| 2 | 612 | | ); |
| | 613 | | } |
| | 614 | |
|
| | 615 | |
|
| | 616 | | /// <summary> |
| | 617 | | /// Adds authentication and authorization middleware to the Kestrun host. |
| | 618 | | /// </summary> |
| | 619 | | /// <param name="host">The Kestrun host instance.</param> |
| | 620 | | /// <param name="buildSchemes">A delegate to configure authentication schemes.</param> |
| | 621 | | /// <param name="defaultScheme">The default authentication scheme (default is JwtBearer).</param> |
| | 622 | | /// <param name="configureAuthz">Optional authorization policy configuration.</param> |
| | 623 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 624 | | internal static KestrunHost AddAuthentication(this KestrunHost host, |
| | 625 | | Action<AuthenticationBuilder> buildSchemes, // ← unchanged |
| | 626 | | string defaultScheme = JwtBearerDefaults.AuthenticationScheme, |
| | 627 | | Action<AuthorizationOptions>? configureAuthz = null) |
| | 628 | | { |
| 22 | 629 | | _ = host.AddService(services => |
| 22 | 630 | | { |
| 22 | 631 | | var ab = services.AddAuthentication(defaultScheme); |
| 22 | 632 | | buildSchemes(ab); // Basic + JWT here |
| 22 | 633 | |
|
| 22 | 634 | | // make sure UseAuthorization() can find its services |
| 22 | 635 | | _ = configureAuthz is null ? services.AddAuthorization() : services.AddAuthorization(configureAuthz); |
| 41 | 636 | | }); |
| | 637 | |
|
| 22 | 638 | | return host.Use(app => |
| 22 | 639 | | { |
| 22 | 640 | | _ = app.UseAuthentication(); |
| 22 | 641 | | _ = app.UseAuthorization(); |
| 44 | 642 | | }); |
| | 643 | | } |
| | 644 | |
|
| | 645 | |
|
| | 646 | | /// <summary> |
| | 647 | | /// Adds authorization services to the Kestrun host. |
| | 648 | | /// </summary> |
| | 649 | | /// <param name="host">The Kestrun host instance.</param> |
| | 650 | | /// <param name="cfg">Optional configuration for authorization options.</param> |
| | 651 | | /// <returns>The configured KestrunHost instance.</returns> |
| | 652 | | public static KestrunHost AddAuthorization(this KestrunHost host, Action<AuthorizationOptions>? cfg = null) |
| | 653 | | { |
| 1 | 654 | | return host.AddService(s => |
| 1 | 655 | | { |
| 1 | 656 | | _ = cfg == null ? s.AddAuthorization() : s.AddAuthorization(cfg); |
| 2 | 657 | | }); |
| | 658 | | } |
| | 659 | |
|
| | 660 | | /// <summary> |
| | 661 | | /// Checks if the specified authentication scheme is registered in the Kestrun host. |
| | 662 | | /// </summary> |
| | 663 | | /// <param name="host">The Kestrun host instance.</param> |
| | 664 | | /// <param name="schemeName">The name of the authentication scheme to check.</param> |
| | 665 | | /// <returns>True if the scheme is registered; otherwise, false.</returns> |
| | 666 | | public static bool HasAuthScheme(this KestrunHost host, string schemeName) |
| | 667 | | { |
| 15 | 668 | | var schemeProvider = host.App.Services.GetRequiredService<IAuthenticationSchemeProvider>(); |
| 15 | 669 | | var scheme = schemeProvider.GetSchemeAsync(schemeName).GetAwaiter().GetResult(); |
| 15 | 670 | | return scheme != null; |
| | 671 | | } |
| | 672 | |
|
| | 673 | | // Helper to copy values from a user-supplied CookieAuthenticationOptions instance to the instance |
| | 674 | | // created by the framework inside AddCookie(). Reassigning the local variable (opts = source) would |
| | 675 | | // not work because only the local reference changes – the framework keeps the original instance. |
| | 676 | | private static void CopyCookieAuthenticationOptions(CookieAuthenticationOptions source, CookieAuthenticationOptions |
| | 677 | | { |
| | 678 | | // Paths & return URL |
| 0 | 679 | | target.LoginPath = source.LoginPath; |
| 0 | 680 | | target.LogoutPath = source.LogoutPath; |
| 0 | 681 | | target.AccessDeniedPath = source.AccessDeniedPath; |
| 0 | 682 | | target.ReturnUrlParameter = source.ReturnUrlParameter; |
| | 683 | |
|
| | 684 | | // Expiration & sliding behavior |
| 0 | 685 | | target.ExpireTimeSpan = source.ExpireTimeSpan; |
| 0 | 686 | | target.SlidingExpiration = source.SlidingExpiration; |
| | 687 | |
|
| | 688 | | // Cookie builder settings |
| | 689 | | // (Cookie is always non-null; copy primitive settings) |
| 0 | 690 | | target.Cookie.Name = source.Cookie.Name; |
| 0 | 691 | | target.Cookie.Path = source.Cookie.Path; |
| 0 | 692 | | target.Cookie.Domain = source.Cookie.Domain; |
| 0 | 693 | | target.Cookie.HttpOnly = source.Cookie.HttpOnly; |
| 0 | 694 | | target.Cookie.SameSite = source.Cookie.SameSite; |
| 0 | 695 | | target.Cookie.SecurePolicy = source.Cookie.SecurePolicy; |
| 0 | 696 | | target.Cookie.IsEssential = source.Cookie.IsEssential; |
| 0 | 697 | | target.Cookie.MaxAge = source.Cookie.MaxAge; |
| | 698 | |
|
| | 699 | | // Forwarding |
| 0 | 700 | | target.ForwardAuthenticate = source.ForwardAuthenticate; |
| 0 | 701 | | target.ForwardChallenge = source.ForwardChallenge; |
| 0 | 702 | | target.ForwardDefault = source.ForwardDefault; |
| 0 | 703 | | target.ForwardDefaultSelector = source.ForwardDefaultSelector; |
| 0 | 704 | | target.ForwardForbid = source.ForwardForbid; |
| 0 | 705 | | target.ForwardSignIn = source.ForwardSignIn; |
| 0 | 706 | | target.ForwardSignOut = source.ForwardSignOut; |
| | 707 | |
|
| | 708 | | // Data protection / ticket / session |
| 0 | 709 | | target.TicketDataFormat = source.TicketDataFormat; |
| 0 | 710 | | target.DataProtectionProvider = source.DataProtectionProvider; |
| 0 | 711 | | target.SessionStore = source.SessionStore; |
| | 712 | |
|
| | 713 | | // Events & issuer |
| 0 | 714 | | if (source.Events is not null) |
| | 715 | | { |
| 0 | 716 | | target.Events = source.Events; |
| | 717 | | } |
| 0 | 718 | | target.EventsType = source.EventsType; |
| 0 | 719 | | target.ClaimsIssuer = source.ClaimsIssuer; |
| 0 | 720 | | } |
| | 721 | |
|
| | 722 | | /// <summary> |
| | 723 | | /// Checks if the specified authorization policy is registered in the Kestrun host. |
| | 724 | | /// </summary> |
| | 725 | | /// <param name="host">The Kestrun host instance.</param> |
| | 726 | | /// <param name="policyName">The name of the authorization policy to check.</param> |
| | 727 | | /// <returns>True if the policy is registered; otherwise, false.</returns> |
| | 728 | | public static bool HasAuthPolicy(this KestrunHost host, string policyName) |
| | 729 | | { |
| 14 | 730 | | var policyProvider = host.App.Services.GetRequiredService<IAuthorizationPolicyProvider>(); |
| 14 | 731 | | var policy = policyProvider.GetPolicyAsync(policyName).GetAwaiter().GetResult(); |
| 14 | 732 | | return policy != null; |
| | 733 | | } |
| | 734 | | } |