180 lines
5.5 KiB
C#
180 lines
5.5 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.
|
|
// Keep secrets in files to avoid exposing them via process environment variables.
|
|
var secretsDirectory = builder.Configuration["K8S_SECRETS_PATH"] ?? "/var/run/secrets/maintenancepages";
|
|
if (Directory.Exists(secretsDirectory))
|
|
{
|
|
builder.Configuration.AddKeyPerFile(secretsDirectory, optional: true, reloadOnChange: true);
|
|
}
|
|
|
|
var primaryDbConnection = builder.Configuration.GetConnectionString("PrimaryDb");
|
|
var groupLookupDbConnection = builder.Configuration.GetConnectionString("GroupLookupDb");
|
|
var adminGroupSource = builder.Configuration[AuthEnvironment.AdminGroupSource] ?? AdminGroupSources.Max;
|
|
|
|
if (string.IsNullOrWhiteSpace(primaryDbConnection))
|
|
{
|
|
throw new InvalidOperationException("Missing connection string: ConnectionStrings:PrimaryDb");
|
|
}
|
|
|
|
builder.Services.AddDbContext<AppDbContext>(options =>
|
|
{
|
|
options.UseSqlServer(primaryDbConnection);
|
|
});
|
|
builder.Services.AddMemoryCache();
|
|
builder.Services.AddSingleton<ITicketStore, MemoryCacheTicketStore>();
|
|
|
|
if (adminGroupSource.Equals(AdminGroupSources.Ad, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (string.IsNullOrWhiteSpace(groupLookupDbConnection))
|
|
{
|
|
throw new InvalidOperationException(
|
|
"Missing connection string: ConnectionStrings:GroupLookupDb when AUTH_GROUP_SOURCE=AD");
|
|
}
|
|
|
|
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";
|
|
});
|
|
builder.Services
|
|
.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
|
|
.Configure<ITicketStore>((options, ticketStore) =>
|
|
{
|
|
options.SessionStore = ticketStore;
|
|
});
|
|
|
|
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("/app-error");
|
|
app.UseHsts();
|
|
}
|
|
|
|
app.UseHttpsRedirection();
|
|
app.UseStaticFiles();
|
|
|
|
app.UseRouting();
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
app.MapGet("/healthz", () => Results.Ok("ok")).AllowAnonymous();
|
|
|
|
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();
|
|
|