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