using Sentry.AspNetCore; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using FluentValidation.AspNetCore; using Heimdall.Application; using Heimdall.Application.Services; using Heimdall.Infrastructure; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.BackgroundJobs; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Api.Hubs; using Heimdall.Web.Services; using Hangfire; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using MudBlazor.Services; using Scalar.AspNetCore; var builder = WebApplication.CreateBuilder(args); // ── Use shared service configuration ────────────────────────────── Program.ConfigureServices(builder); var app = builder.Build(); // ── Use shared middleware configuration ─────────────────────────── Program.ConfigureMiddleware(app); // ── Apply pending database migrations ──────────────────────────────── // Retry with exponential backoff to handle container startup races where // PostgreSQL accepts TCP connections but isn't ready to serve queries yet. // Migrations run by default in every environment EXCEPT Testing // (appsettings.Testing.json sets Database:MigrateOnStartup=false; test // factories opt back in explicitly when they need the schema). var migrateOnStartup = builder.Configuration.GetValue("Database:MigrateOnStartup") ?? !app.Environment.IsEnvironment("Testing"); if (migrateOnStartup) { await Program.ApplyMigrationsAsync(app); } // ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ── var isTesting = app.Environment.IsEnvironment("Testing"); var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default"); if (!isTesting && !string.IsNullOrEmpty(pgConnStr)) { using (var scope = app.Services.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager); } } // ── Seed Identity roles (required in ALL environments, including Testing) ─ // This must run before any user registration — AuthService.AddToRoleAsync // throws "Role X does not exist" if the role hasn't been created yet. await Program.SeedAsync(app, builder.Configuration); app.Run(); // ─── DTO for the cookie sign-in request ─────────────────────────── internal sealed record SignInRequest( string AccessToken); // Partial class declaration so WebApplicationFactory // works in integration tests. public partial class Program { // Shared JWT validation parameters — single source of truth for auth. internal static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), ValidateIssuer = true, ValidIssuer = issuer, ValidateAudience = true, ValidAudience = audience, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; /// /// Creates a configured WebApplication suitable for testing. /// Used by E2E tests to start a real Kestrel server. /// public static WebApplication CreateTestApplication(string[]? args = null, Action? configure = null) { var builder = WebApplication.CreateBuilder(args ?? []); // Under xUnit the entry assembly is "testhost", so the framework would // look for "testhost.staticwebassets.runtime.json" and serve none of the // Blazor framework files (_framework/blazor.web.js etc.). Pin the app name // to Heimdall.Web and load the static web assets manifest copied next to // the test assembly so the Blazor runtime, MudBlazor CSS and wwwroot serve. builder.Environment.ApplicationName = "Heimdall.Web"; builder.WebHost.UseStaticWebAssets(); // Allow test-specific overrides BEFORE service configuration // (so config values are available when services read them) configure?.Invoke(builder); // Apply the standard service configuration ConfigureServices(builder); var app = builder.Build(); ConfigureMiddleware(app); return app; } /// /// Applies pending EF migrations with retry/backoff. Shared between the /// normal entry point and test hosts (E2E) so both boot paths behave identically. /// public static async Task ApplyMigrationsAsync(WebApplication app) { // Use a 5-minute overall timeout so startup doesn't hang indefinitely // if the database is unreachable. Each retry respects this token. using var migrationCts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); var migrationCt = migrationCts.Token; using (var scope = app.Services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService>(); var db = scope.ServiceProvider.GetRequiredService(); var maxRetries = 5; var retryDelay = TimeSpan.FromSeconds(2); for (var attempt = 1; attempt <= maxRetries; attempt++) { try { migrationCt.ThrowIfCancellationRequested(); logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries); db.Database.Migrate(); logger.LogInformation("Database migrations applied successfully"); break; } catch (OperationCanceledException) { logger.LogCritical("Database migration timed out after 5 minutes."); throw; } catch (Exception ex) when (attempt < maxRetries) { logger.LogWarning(ex, "Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...", attempt, maxRetries, retryDelay.TotalSeconds); await Task.Delay(retryDelay, migrationCt); retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); } catch (Exception ex) { logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries); throw; } } } } /// /// Seeds Identity roles, default groups and (optionally) the demo admin + demo site. /// Idempotent — safe to call on every startup and from test hosts. /// public static async Task SeedAsync(WebApplication app, IConfiguration configuration) { using var seedScope = app.Services.CreateScope(); var roleManager = seedScope.ServiceProvider .GetRequiredService>(); var userManager = seedScope.ServiceProvider .GetRequiredService>(); foreach (var roleName in AppRoles.All) { if (!await roleManager.RoleExistsAsync(roleName)) { await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName)); } } // Seed default groups (idempotent) var groupDb = seedScope.ServiceProvider.GetRequiredService(); var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" }; foreach (var groupName in defaultGroups) { if (!await groupDb.Groups.AnyAsync(g => g.Name == groupName)) { groupDb.Groups.Add(new Heimdall.Domain.Entities.Group(groupName, groupName switch { "Administrateurs" => "Accès complet à toutes les fonctionnalités", "Superviseurs" => "Gestion des sites, caméras et événements", "Visiteurs" => "Consultation en lecture seule", "Techniciens" => "Maintenance technique et support", _ => null })); } } await groupDb.SaveChangesWithRetryAsync(); // Seed demo admin + demo site when explicitly enabled (dev & E2E hosts) if (configuration.GetValue("Seed:DemoOnStartup", false)) { var adminLogin = configuration.GetValue("Seed:AdminLogin") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN") ?? "admin@heimdall.test"; var testAdmin = await userManager.FindByEmailAsync(adminLogin); if (testAdmin is null) { testAdmin = new Heimdall.Domain.Entities.AppUser { UserName = adminLogin, Email = adminLogin, DisplayName = configuration.GetValue("Seed:AdminDisplayName") ?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME") ?? "Admin" }; var adminPassword = configuration["Seed:AdminPassword"] ?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD") ?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup."); await userManager.CreateAsync(testAdmin, adminPassword); await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin); } var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo"); if (demoSite is null) { demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris"); groupDb.Sites.Add(demoSite); await groupDb.SaveChangesWithRetryAsync(); } } } internal static void ConfigureServices(WebApplicationBuilder builder) { // ── Sentry (GlitchTip) — error tracking, performance & structured logs ── // Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn // Fallback: legacy SENTRY_DSN env var (Docker backward compat) // Neither set → DSN is null → Sentry SDK no-ops gracefully var sentryDsn = builder.Configuration["Sentry:Dsn"] ?? Environment.GetEnvironmentVariable("SENTRY_DSN"); if (!string.IsNullOrEmpty(sentryDsn)) { builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => { options.Dsn = sentryDsn; // ── Env & Release ──────────────────────────────────────── // Environment is auto-read from IHostingEnvironment // Release should be explicitly set (e.g. "heimdall@1.2.3") options.Release = builder.Configuration["Sentry:Release"] ?? Environment.GetEnvironmentVariable("SENTRY_RELEASE"); // ── Error sampling ────────────────────────────────────── options.SampleRate = 1.0f; // 100% errors (adjust if volume too high) options.AttachStacktrace = true; // Stack traces even on CaptureMessage options.MaxBreadcrumbs = 100; // Breadcrumb buffer size options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; // ── Tracing (Performance) ─────────────────────────────── // GlitchTip counts every transaction as an event. // 0.05 = 5% sample = good signal-to-noise in production. options.TracesSampleRate = double.Parse( builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05", System.Globalization.CultureInfo.InvariantCulture); // ── Request body capture ──────────────────────────────── options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small; // ── Structured logs (v5.14+) ──────────────────────────── // Enables SentrySdk.Logger.LogInfo() etc. options.EnableLogs = true; // ── GlitchTip-specific: disable unsupported features ──── // Release Health / Sessions are NOT supported by GlitchTip options.AutoSessionTracking = false; // ── PII & GDPR ────────────────────────────────────────── options.SendDefaultPii = false; // Explicit RGPD-safe default options.ServerName = null; // Never send hostname // ── Enhanced diagnostics ──────────────────────────────── options.CaptureBlockingCalls = true; // Detect .Result / .Wait() options.CaptureFailedRequests = true; // Capture HttpClient 4xx/5xx options.IncludeActivityData = true; // DiagnosticSource Activity // ── Stack traces ──────────────────────────────────────── options.StackTraceMode = Sentry.StackTraceMode.Enhanced; // ── BeforeSend — scrub PII before it leaves the SDK ──── options.SetBeforeSend((sentryEvent, hint) => { // Never send server name (already null above, belt-and-suspenders) sentryEvent.ServerName = null; // Remove sensitive extras if (sentryEvent.Extra?.ContainsKey("password") == true) (sentryEvent.Extra as IDictionary)?.Remove("password"); if (sentryEvent.Extra?.ContainsKey("token") == true) (sentryEvent.Extra as IDictionary)?.Remove("token"); if (sentryEvent.Extra?.ContainsKey("secret") == true) (sentryEvent.Extra as IDictionary)?.Remove("secret"); return sentryEvent; }); // ── BeforeBreadcrumb — filter noisy breadcrumbs ──────── options.SetBeforeBreadcrumb(breadcrumb => breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting" ? null : breadcrumb); }); } // ── Startup diagnostics ──────────────────────────────────────── var sentryStatus = string.IsNullOrEmpty(sentryDsn) ? "NOT CONFIGURED — errors will NOT be reported to GlitchTip" : "configured (" + sentryDsn[..sentryDsn.IndexOf('@')] + "@...)"; Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}"); Console.WriteLine($"[DIAG] Environment: {builder.Environment.EnvironmentName}"); Console.WriteLine($"[DIAG] Data Protection keys dir: /var/lib/heimdall/dp-keys"); Console.WriteLine($"[DIAG] Demo seeding: {(builder.Configuration.GetValue("Seed:DemoOnStartup", false) ? "enabled" : "disabled (set Seed:DemoOnStartup=true to enable)")}"); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // In-memory cache — required by INotificationRateLimiter (singleton) builder.Services.AddMemoryCache(); // ── Authentication ────────────────────────────────────────────── var jwtKey = builder.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") ?? throw new InvalidOperationException("JWT:Key is not configured"); var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = "/login"; options.LogoutPath = "/_auth/signout"; options.AccessDeniedPath = "/not-found"; options.Cookie.Name = ".Heimdall.Auth"; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; // Use SameAsRequest to support both HTTP and HTTPS deployments // In production with HTTPS, the cookie will still be secure options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.SlidingExpiration = true; // Add logging events options.Events = new CookieAuthenticationEvents { OnRedirectToLogin = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); logger.LogWarning("Redirect to login: {Path} -> {LoginPath}", context.Request.Path, options.LoginPath); context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }, OnRedirectToAccessDenied = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); logger.LogWarning("Access denied: {Path} -> {AccessDeniedPath}", context.Request.Path, options.AccessDeniedPath); context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }, OnValidatePrincipal = context => { var logger = context.HttpContext.RequestServices.GetRequiredService>(); logger.LogDebug("Validating principal for {Path}", context.HttpContext.Request.Path); return Task.CompletedTask; } }; }) .AddJwtBearer("JwtBearer", options => { options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience); options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) context.Token = accessToken; return Task.CompletedTask; } }; }) .AddScheme("ApiKey", null); builder.Services.AddAuthorizationCore(options => { var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct(); foreach (var permission in allPermissions) options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission)); // Policy used by AuthController (register-admin, user management). // Not a permission claim but a role-based gate for admin-only actions. options.AddPolicy("AdminUsers", policy => policy.RequireRole(AppRoles.Admin)); }); builder.Services.AddCascadingAuthenticationState(); builder.Services.AddScoped(); builder.Services.AddScoped( sp => sp.GetRequiredService()); // ── MudBlazor ───────────────────────────────────────────────────── builder.Services.AddMudServices(config => { config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; config.SnackbarConfiguration.PreventDuplicates = true; config.SnackbarConfiguration.ShowCloseIcon = true; config.SnackbarConfiguration.VisibleStateDuration = 4000; }); // ── Rate Limiting ─────────────────────────────────────────────── builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = 429; options.AddFixedWindowLimiter("Auth", opt => { opt.PermitLimit = 10; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); options.AddFixedWindowLimiter("Api", opt => { opt.PermitLimit = 200; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); // 2FA codes are high-value, low-volume: tighter limit than the login endpoint. options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); }); // ── Controllers (REST API) ──────────────────────────────────────── builder.Services.AddControllers(options => options.Filters.Add()) .AddJsonOptions(options => { // Serialize enums as strings in API responses (e.g. Agent.Status, // Camera.Status) — otherwise the Blazor client fails to parse // numeric enum values into its string-typed models. options.JsonSerializerOptions.Converters.Add( new System.Text.Json.Serialization.JsonStringEnumConverter()); }) // Explicitly register the Web assembly as an application part. // AddMvcCore only auto-discovers Assembly.GetEntryAssembly(), which is // the test host ("testhost") when CreateTestApplication runs under // xUnit — without this, no /api/* controller is ever mapped in E2E. .AddApplicationPart(typeof(Program).Assembly); builder.Services.AddFluentValidationAutoValidation(); builder.Services.Configure(opts => opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); builder.Services.AddSignalR(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddOpenApi(); // ── Application & Infrastructure layers ────────────────────────── builder.Services.AddApplication(); builder.Services.AddInfrastructure(builder.Configuration); // AddIdentity (inside AddInfrastructure) sets Identity.Application as the // default authenticate/challenge scheme. But /_auth/signin signs the // ".Heimdall.Auth" cookie with the "Cookies" scheme. If the default stays // on Identity.Application, UseAuthentication tries to validate the ticket // with a DIFFERENT Data Protection purpose -> the cookie is never accepted // and full page reloads always bounce back to /login. builder.Services.Configure(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }); // Configure Identity cookie AFTER AddInfrastructure (which calls AddIdentity) // AddIdentity sets default paths (/Account/Login) that must be overridden builder.Services.ConfigureApplicationCookie(options => { options.LoginPath = "/login"; options.LogoutPath = "/_auth/signout"; options.AccessDeniedPath = "/not-found"; options.Cookie.Name = ".Heimdall.Auth"; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.SlidingExpiration = true; }); // ── Background jobs (skipped in Testing) ──────────────────────── var isTesting = builder.Environment.IsEnvironment("Testing"); var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") ?? builder.Configuration.GetConnectionString("Default"); if (!isTesting && !string.IsNullOrEmpty(connectionString)) builder.Services.AddBackgroundJobs(builder.Configuration); // ── HTTP client ────────────────────────────────────────────────── // Blazor Server monolith: the UI and the API run in the same process, // so requests target the SAME origin as the browser by default. An // explicit ApiBaseUrl (config/env) overrides that for external APIs. builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddTransient(); builder.Services.AddTransient(); var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration); var apiBaseUrl = apiBaseUrlConfigured ? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)! : ApiBaseUrlResolver.PlaceholderBase; builder.Services.AddHttpClient("HeimdallApi", client => { var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/"; client.BaseAddress = new Uri(baseUrl); client.Timeout = TimeSpan.FromSeconds(30); }) .AddHttpMessageHandler() .AddHttpMessageHandler(); if (apiBaseUrlConfigured) Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)"); else Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)"); builder.Services.AddScoped(); } internal static void ConfigureMiddleware(WebApplication app) { if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } // Only enable HTTPS redirection if HTTPS is actually configured on Kestrel. // In production behind a reverse proxy (nginx, Traefik, Caddy), TLS is // terminated at the proxy level — Kestrel runs on HTTP internally, so // this block is intentionally skipped (ASPNETCORE_URLS has no https://). // The proxy handles the HTTP to HTTPS redirect. var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? ""; if (urls.Contains("https://", StringComparison.OrdinalIgnoreCase)) { app.UseHttpsRedirection(); } app.UseStaticFiles(); app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); app.MapRazorComponents().AddInteractiveServerRenderMode(); app.MapControllers(); app.MapHub("/hubs/config"); app.MapHub("/hubs/events"); app.MapHub("/hubs/monitoring"); app.MapHub("/hubs/notifications"); app.MapHub("/hubs/admin"); // Diagnostic: log all mapped endpoints so E2E host mapping issues are visible. if (app.Environment.IsEnvironment("Testing")) { var dataSource = app.Services.GetRequiredService(); var endpoints = dataSource.Endpoints .Select(e => e is Microsoft.AspNetCore.Routing.RouteEndpoint re ? re.RoutePattern.RawText : e.ToString()) .Where(s => !string.IsNullOrEmpty(s)) .OrderBy(s => s, StringComparer.Ordinal) .ToList(); Console.WriteLine($"[DIAG] Mapped endpoints ({endpoints.Count}): {string.Join(", ", endpoints)}"); } if (app.Environment.IsDevelopment()) { app.MapOpenApi(); app.MapScalarApiReference(); } var allowedOrigins = app.Configuration["Cors:AllowedOrigins"]?.Split(',') ?? ["https://localhost:5001"]; app.UseCors(options => { var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*"; if (isWildcard) { options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); } else { options.WithOrigins(allowedOrigins).AllowCredentials() .AllowAnyHeader().WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"); } }); app.UseRateLimiter(); MapAuthEndpoints(app); } internal static void MapAuthEndpoints(WebApplication app) { var jwtKey = app.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") ?? ""; var jwtIssuer = app.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; var jwtAudience = app.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger logger) => { if (string.IsNullOrEmpty(request.AccessToken)) return Results.BadRequest(new { error = "AccessToken is required" }); try { var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(request.AccessToken, GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _); var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; var email = principal.FindFirst(ClaimTypes.Email)?.Value; var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email)) return Results.BadRequest(new { error = "Invalid token: missing user claims" }); var claims = new List { new(ClaimTypes.NameIdentifier, userId), new(ClaimTypes.Email, email), new(ClaimTypes.Name, displayName ?? email), }; foreach (var role in principal.FindAll(ClaimTypes.Role)) claims.Add(new Claim(ClaimTypes.Role, role.Value)); foreach (var permission in principal.FindAll("permission")) claims.Add(new Claim("permission", permission.Value)); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Results.Ok(); } catch (SecurityTokenExpiredException) { return Results.Unauthorized(); } catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); } }); app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => { await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Ok(); }); } }