Files
maintenancepages/Program.cs
T
2026-03-05 09:15:19 -05:00

165 lines
4.9 KiB
C#

using maintenance.Authentication.Abstractions;
using maintenance.Authentication.Configuration;
using maintenance.Authentication.Core;
using maintenance.Authentication.Providers.AdfsWsFed;
using maintenance.Authentication.Providers.Oidc;
using maintenance.Data;
using maintenance.Data.Seed;
using maintenance.Services.Pages;
using maintenance.Services.Templates;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
builder.Configuration.AddJsonFile("FutureSecrets.json", optional: true, reloadOnChange: true);
}
// Support Kubernetes mounted secrets (key-per-file) and env var secrets.
// Add env vars again after custom providers so Secret-backed env values win precedence.
var secretsDirectory = builder.Configuration["K8S_SECRETS_PATH"] ?? "/var/run/secrets/maintenancepages";
if (Directory.Exists(secretsDirectory))
{
builder.Configuration.AddKeyPerFile(secretsDirectory, optional: true, reloadOnChange: true);
}
builder.Configuration.AddEnvironmentVariables();
var primaryDbConnection = builder.Configuration.GetConnectionString("PrimaryDb");
var groupLookupDbConnection = builder.Configuration.GetConnectionString("GroupLookupDb");
if (string.IsNullOrWhiteSpace(primaryDbConnection))
{
throw new InvalidOperationException("Missing connection string: ConnectionStrings:PrimaryDb");
}
if (string.IsNullOrWhiteSpace(groupLookupDbConnection))
{
throw new InvalidOperationException("Missing connection string: ConnectionStrings:GroupLookupDb");
}
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(primaryDbConnection);
});
builder.Services.AddDbContext<GroupLookupDbContext>(options =>
{
options.UseSqlServer(groupLookupDbConnection);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
builder.Services.AddScoped<ITemplateService, TemplateService>();
builder.Services.AddScoped<IManagedPageService, ManagedPageService>();
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin", "AdminOnly");
});
builder.Services.AddScoped<IClaimsTransformation, AdminRoleClaimsTransformation>();
builder.Services.AddSingleton<IIdentityContextFactory, IdentityContextFactory>();
builder.Services.AddSingleton<IAuthProvider, AdfsWsFedAuthProvider>();
builder.Services.AddSingleton<IAuthProvider, OidcAuthProvider>();
var authMode = builder.Configuration[AuthEnvironment.AuthMode] ?? AuthModes.WsFed;
var challengeScheme = authMode.Equals(AuthModes.WsFed, StringComparison.OrdinalIgnoreCase)
? AdfsWsFedAuthProvider.Scheme
: OidcAuthProvider.Scheme;
var authBuilder = builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = challengeScheme;
});
authBuilder.AddCookie(options =>
{
options.Cookie.Name = "errorpages.auth";
options.AccessDeniedPath = "/AccessDenied";
});
var providers = new IAuthProvider[]
{
new AdfsWsFedAuthProvider(),
new OidcAuthProvider()
};
var provider = providers.FirstOrDefault(p =>
p.Mode.Equals(authMode, StringComparison.OrdinalIgnoreCase));
if (provider is null)
{
throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}");
}
provider.Configure(authBuilder, builder.Configuration);
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.AddPolicy("AdminOnly", policy => policy.RequireRole(AuthRoles.Admin));
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
try
{
await TemplateSeeder.SeedAsync(db);
await ManagedPageSeeder.SeedAsync(db);
}
catch
{
// Seed is best-effort for offline/dev environments.
}
}
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/whoami", (ClaimsPrincipal user, IIdentityContextFactory identityFactory) =>
{
var identity = identityFactory.Create(user);
var claims = user.Claims
.Select(c => new { c.Type, c.Value })
.OrderBy(c => c.Type)
.ToArray();
return Results.Ok(new
{
identity.UserId,
identity.DisplayName,
identity.Groups,
identity.Roles,
IsAuthenticated = user.Identity?.IsAuthenticated ?? false,
AuthenticationType = user.Identity?.AuthenticationType,
Claims = claims
});
})
.RequireAuthorization();
app.MapRazorPages();
app.Run();