using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; using ZB.MOM.WW.MxGateway.Server.Configuration; namespace ZB.MOM.WW.MxGateway.Server.Dashboard; /// /// Extension methods for configuring the gateway dashboard services. /// public static class DashboardServiceCollectionExtensions { /// /// Registers all dashboard services, authentication, and Razor components. /// /// Service collection to register services. public static IServiceCollection AddGatewayDashboard(this IServiceCollection services) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); services.AddHttpContextAccessor(); services.AddAntiforgery(); services.AddCascadingAuthenticationState(); services.AddRazorComponents() .AddInteractiveServerComponents(); services.AddSignalR(); services .AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme) .AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions => { cookieOptions.Cookie.Name = DashboardAuthenticationDefaults.CookieName; cookieOptions.Cookie.HttpOnly = true; cookieOptions.Cookie.SameSite = SameSiteMode.Strict; // SecurePolicy is bound via PostConfigure below so it can honour // DashboardOptions.RequireHttpsCookie (default Always; dev HTTP // deployments set RequireHttpsCookie=false to use SameAsRequest). cookieOptions.Cookie.Path = "/"; cookieOptions.LoginPath = "/login"; cookieOptions.LogoutPath = "/logout"; cookieOptions.AccessDeniedPath = "/denied"; cookieOptions.ExpireTimeSpan = TimeSpan.FromHours(8); cookieOptions.SlidingExpiration = true; }) .AddScheme( DashboardAuthenticationDefaults.HubAuthenticationScheme, _ => { }); services.AddOptions(DashboardAuthenticationDefaults.AuthenticationScheme) .Configure>((cookieOptions, gatewayOptions) => { cookieOptions.Cookie.SecurePolicy = gatewayOptions.Value.Dashboard.RequireHttpsCookie ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest; }); services.AddAuthorization(authorization => { authorization.AddPolicy( DashboardAuthenticationDefaults.ViewerPolicy, policy => policy.AddRequirements(DashboardAuthorizationRequirement.AnyDashboardRole)); authorization.AddPolicy( DashboardAuthenticationDefaults.AdminPolicy, policy => policy.AddRequirements(DashboardAuthorizationRequirement.AdminOnly)); authorization.AddPolicy( DashboardAuthenticationDefaults.HubClientsPolicy, policy => policy .AddAuthenticationSchemes( DashboardAuthenticationDefaults.AuthenticationScheme, DashboardAuthenticationDefaults.HubAuthenticationScheme) .AddRequirements(DashboardAuthorizationRequirement.AnyDashboardRole)); }); services.AddSingleton(); return services; } }