57 lines
2.4 KiB
C#
57 lines
2.4 KiB
C#
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<IDashboardSnapshotService, DashboardSnapshotService>();
|
|
services.AddSingleton<IDashboardAuthenticator, DashboardAuthenticator>();
|
|
services.AddHttpContextAccessor();
|
|
services.AddAntiforgery();
|
|
services.AddCascadingAuthenticationState();
|
|
services.AddRazorComponents()
|
|
.AddInteractiveServerComponents();
|
|
services
|
|
.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme)
|
|
.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme);
|
|
services.AddOptions<CookieAuthenticationOptions>(DashboardAuthenticationDefaults.AuthenticationScheme)
|
|
.Configure<IOptions<GatewayOptions>>(ConfigureCookieOptions);
|
|
services.AddAuthorization(options =>
|
|
{
|
|
options.AddPolicy(
|
|
DashboardAuthenticationDefaults.AuthorizationPolicy,
|
|
policy => policy.AddRequirements(new DashboardAuthorizationRequirement()));
|
|
});
|
|
services.AddSingleton<IAuthorizationHandler, DashboardAuthorizationHandler>();
|
|
|
|
return services;
|
|
}
|
|
|
|
private static void ConfigureCookieOptions(
|
|
CookieAuthenticationOptions cookieOptions,
|
|
IOptions<GatewayOptions> 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;
|
|
}
|
|
}
|