using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using MxGateway.Server.Configuration; namespace MxGateway.Server.Dashboard; public static class DashboardServiceCollectionExtensions { public static IServiceCollection AddGatewayDashboard(this IServiceCollection services) { services.AddSingleton(); services.AddSingleton(); services.AddHttpContextAccessor(); services.AddAntiforgery(); services.AddCascadingAuthenticationState(); services.AddRazorComponents() .AddInteractiveServerComponents(); services .AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme) .AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme); services.AddOptions(DashboardAuthenticationDefaults.AuthenticationScheme) .Configure>(ConfigureCookieOptions); services.AddAuthorization(options => { options.AddPolicy( DashboardAuthenticationDefaults.AuthorizationPolicy, policy => policy.AddRequirements(new DashboardAuthorizationRequirement())); }); services.AddSingleton(); return services; } private static void ConfigureCookieOptions( CookieAuthenticationOptions cookieOptions, IOptions gatewayOptions) { string pathBase = gatewayOptions.Value.Dashboard.PathBase.TrimEnd('/'); if (string.IsNullOrWhiteSpace(pathBase)) { pathBase = "/dashboard"; } cookieOptions.Cookie.Name = DashboardAuthenticationDefaults.CookieName; cookieOptions.Cookie.HttpOnly = true; cookieOptions.Cookie.SecurePolicy = CookieSecurePolicy.Always; cookieOptions.Cookie.SameSite = SameSiteMode.Strict; cookieOptions.Cookie.Path = "/"; cookieOptions.LoginPath = $"{pathBase}/login"; cookieOptions.LogoutPath = $"{pathBase}/logout"; cookieOptions.AccessDeniedPath = $"{pathBase}/denied"; cookieOptions.ExpireTimeSpan = TimeSpan.FromHours(8); cookieOptions.SlidingExpiration = true; } }