| | | 1 | | |
| | | 2 | | using Microsoft.AspNetCore.Authentication; |
| | | 3 | | using Microsoft.AspNetCore.Authentication.Cookies; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection.Extensions; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace Kestrun.Authentication; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Extension methods for <see cref="AuthenticationBuilder"/> to add cookie authentication. |
| | | 11 | | /// </summary> |
| | | 12 | | internal static class AuthenticationBuilderExtensions |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Adds cookie authentication to <see cref="AuthenticationBuilder"/> using the specified scheme. |
| | | 16 | | /// <para> |
| | | 17 | | /// Cookie authentication uses a HTTP cookie persisted in the client to perform authentication. |
| | | 18 | | /// </para> |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param> |
| | | 21 | | /// <param name="authenticationScheme">The authentication scheme.</param> |
| | | 22 | | /// <param name="displayName">A display name for the authentication handler.</param> |
| | | 23 | | /// <param name="configureOptions">A delegate to configure <see cref="CookieAuthenticationOptions"/>.</param> |
| | | 24 | | /// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns> |
| | | 25 | | public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, strin |
| | | 26 | | { |
| | 0 | 27 | | builder.Services.TryAddEnumerable( |
| | 0 | 28 | | ServiceDescriptor.Singleton< |
| | 0 | 29 | | IPostConfigureOptions<CookieAuthenticationOptions>, |
| | 0 | 30 | | PostConfigureCookieAuthenticationOptions>()); |
| | | 31 | | |
| | 0 | 32 | | _ = builder.Services |
| | 0 | 33 | | .AddOptions<CookieAuthenticationOptions>(authenticationScheme) |
| | 0 | 34 | | .Validate(o => o.Cookie.Expiration == null, |
| | 0 | 35 | | "Cookie.Expiration is ignored, use ExpireTimeSpan instead."); |
| | | 36 | | |
| | 0 | 37 | | return builder.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, display |
| | 0 | 38 | | { |
| | 0 | 39 | | if (configureOptions is null) |
| | 0 | 40 | | { |
| | 0 | 41 | | return; |
| | 0 | 42 | | } |
| | 0 | 43 | | |
| | 0 | 44 | | // Start from a fresh Kestrun-friendly options object |
| | 0 | 45 | | var userOptions = new CookieAuthOptions(); |
| | 0 | 46 | | |
| | 0 | 47 | | // Let the caller configure all the rich stuff |
| | 0 | 48 | | configureOptions(userOptions); |
| | 0 | 49 | | |
| | 0 | 50 | | // Push everything into the real framework options |
| | 0 | 51 | | userOptions.ApplyTo(options); |
| | 0 | 52 | | }); |
| | | 53 | | } |
| | | 54 | | } |