GNMON-001 M6: OIDC-faehiges Dashboard v0.2.0 (App + Rolle + Doku)

App (Ghostnet.Dashboard, baut fehlerfrei mit 0 Warnungen, .NET 10):
- OIDC konfigurationsgetrieben (Auth:Enabled/Authority/ClientId in
  appsettings.json, Secret nur via ENV Auth__ClientSecret), Authorization
  Code Flow mit PKCE, Cookie-Schema
- KeycloakRealmRolesClaimTransformation mappt realm_access.roles auf
  Role-Claims; Policy DashboardAccess erfordert Realm-Rolle
  dashboard-admin (im Off-Modus permissive)
- Endpoint-Autorisierung an MapRazorComponents().RequireAuthorization()
  (.NET 10: AuthorizeRouteView hat keinen Policy-Parameter mehr),
  UseForwardedHeaders fuer TLS-Terminierung an NPM, /login + /logout
- Paket Microsoft.AspNetCore.Authentication.OpenIdConnect 10.0.14

Rolle/Quadlet: host-lokale, verwaltete Secrets-Datei
/etc/gnmon/dashboard-secrets.env (Owner gn-dashboard, 0640, force: false)
per EnvironmentFile im Quadlet; Image-Default auf v0.2.0 angehoben,
Inventory pinnt v0.2.0; Duplikat gnmon_dashboard_quadlet_dir entfernt;
Containerfile-Kommentar an die keep-id-Entscheidung (GNMON-000 M5) angepasst.

Doku: GNMON-000 (M6-Abschnitt, Verifikation 09.11.2026 nach Host-Neustart,
CT-103-Ansible-Nachbau als erledigt markiert) und GNMON-001 v2.1
(Umsetzungsabweichungen: gn-monitor=986, Braille statt ApexCharts,
Hostname mon.ghostnet.selfhost.eu, offene Punkte 1-4 entschieden).

Externe Freigabe (NPM-Proxyhost + Keycloak-Client gn-dashboard +
Auth__Enabled=true) bleibt Betreiber-Schritt, siehe GNMON-000 M6.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-11-09 05:40:47 +01:00
parent d800a8a661
commit bf0ec37fc1
12 changed files with 334 additions and 39 deletions
@@ -1,5 +1,10 @@
using System.Security.Claims;
using Ghostnet.Dashboard.Components;
using Ghostnet.Dashboard.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
@@ -28,8 +33,77 @@ builder.Services.AddHttpClient<AlertmanagerClient>(client =>
client.Timeout = TimeSpan.FromSeconds(5);
});
// --- OIDC (GNMON-001 section 6, M6) ------------------------------------
// Auth is purely configuration-driven: disabled (workstation/local
// deployments) the DashboardAccess policy authorizes everyone; enabled
// the app requires a Keycloak login with the realm role dashboard-admin.
var authEnabled = builder.Configuration.GetValue<bool>("Auth:Enabled");
if (authEnabled)
{
var authority = builder.Configuration["Auth:Authority"]
?? throw new InvalidOperationException("Auth:Enabled requires Auth:Authority");
var clientId = builder.Configuration["Auth:ClientId"]
?? throw new InvalidOperationException("Auth:Enabled requires Auth:ClientId");
// The client secret never enters the repository or the image; it is
// mounted via the environment (quadlet Environment= or secrets file).
var clientSecret = builder.Configuration["Auth:ClientSecret"]
?? throw new InvalidOperationException(
"Auth:Enabled requires the client secret via Auth:ClientSecret (environment)");
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = authority;
options.ClientId = clientId;
options.ClientSecret = clientSecret;
options.ResponseType = "code"; // authorization code flow + PKCE
options.UsePkce = true;
options.SaveTokens = false;
options.GetClaimsFromUserInfoEndpoint = false;
// Keycloak realm roles live in realm_access.roles; map them onto
// role claims in addition to the claims transformation (the
// transformation also covers identities without a role claim).
options.TokenValidationParameters.RoleClaimType = "role";
options.Scope.Add("openid");
options.Scope.Add("profile");
});
builder.Services.AddSingleton<IClaimsTransformation, KeycloakRealmRolesClaimTransformation>();
}
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("DashboardAccess", policy =>
{
if (authEnabled)
{
// Realm role from Ghost.net (see KeycloakRealmRolesClaimTransformation).
policy.RequireRole("dashboard-admin");
}
else
{
// Local/off mode (workstation dev, M5 loopback deployment):
// no authentication handler is registered, allow anonymous.
policy.RequireAssertion(_ => true);
}
});
});
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();
// TLS terminates at NPM (CT-103); trust its forwarded headers so the
// OIDC redirect URIs and HTTPS checks see the external scheme/host.
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
});
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
@@ -40,10 +114,50 @@ if (!app.Environment.IsDevelopment())
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();
// With auth handlers registered wire the pipeline; disabled (local/off)
// there is no scheme provider and the DashboardAccess policy allows
// anonymous anyway.
if (authEnabled)
{
app.UseAuthentication();
app.UseAuthorization();
}
app.UseAntiforgery();
// Minimal interactive auth endpoints (per-page interactive render mode
// keeps this out of the Blazor circuit; AuthorizeRouteView sends
// unauthenticated users here via RedirectToLogin).
app.MapGet("/login", async (HttpContext context, string? returnUrl) =>
{
if (!authEnabled)
{
context.Response.Redirect("/");
return;
}
await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties { RedirectUri = "/" });
});
app.MapGet("/logout", async (HttpContext context) =>
{
if (authEnabled)
{
await context.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
else
{
context.Response.Redirect("/");
}
});
app.MapStaticAssets();
// Endpoint-level authorization (AuthorizeRouteView lost its Policy
// parameter in .NET 10): unauthenticated requests are challenged by the
// OIDC handler and return to the originally requested page after the
// Keycloak login; authenticated users without the realm role get 403.
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
.AddInteractiveServerRenderMode()
.RequireAuthorization("DashboardAccess");
app.Run();