diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index 41e85a3..b7286bc 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -108,12 +108,19 @@ // Create middleware-level auth cookie so the ASP.NET Core // middleware recognizes the user on subsequent requests. + var cookieOk = true; if (!string.IsNullOrEmpty(result.AccessToken)) { - await AuthHelper.SignInAsync(JsRuntime, + cookieOk = await AuthHelper.SignInAsync(JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken)); } + if (!cookieOk) + { + _errorMessage = "Erreur lors de la création de la session. Veuillez réessayer."; + return; + } + Snackbar.Add("Connexion réussie", Severity.Success); Navigation.NavigateTo(_returnUrl); } diff --git a/src/Heimdall.Web/Components/Pages/Register.razor b/src/Heimdall.Web/Components/Pages/Register.razor index 14f23d5..a9094cb 100644 --- a/src/Heimdall.Web/Components/Pages/Register.razor +++ b/src/Heimdall.Web/Components/Pages/Register.razor @@ -98,12 +98,19 @@ await AuthStateProvider.NotifyLoginAsync(result); // Create middleware-level auth cookie + var cookieOk = true; if (!string.IsNullOrEmpty(result.AccessToken)) { - await AuthHelper.SignInAsync(JsRuntime, + cookieOk = await AuthHelper.SignInAsync(JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken)); } + if (!cookieOk) + { + _errorMessage = "Compte créé mais échec de connexion automatique. Veuillez vous connecter."; + return; + } + Snackbar.Add("Compte créé avec succès", Severity.Success); Navigation.NavigateTo("/dashboard"); } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 36c5f10..982be54 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -1,12 +1,12 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; +using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Web.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.IdentityModel.Tokens; using MudBlazor.Services; @@ -113,6 +113,25 @@ app.UseAuthorization(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); +// ── Health check endpoints for Docker ───────────────────────────── +app.MapGet("/healthz", () => + Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow })); + +app.MapGet("/readyz", async (HttpContext context) => +{ + try + { + using var scope = context.RequestServices.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + _ = await db.Database.CanConnectAsync(); + return Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow }); + } + catch + { + return Results.StatusCode(503); + } +}); + // ── Cookie auth endpoints (called from Blazor via JS fetch) ─────── // /_auth/signin — Validates the JWT access token and creates an auth cookie // /_auth/signout — Clears the authentication cookie on logout @@ -125,13 +144,13 @@ var jwtKey = builder.Configuration["Jwt:Key"] var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; -app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, IAntiforgery antiforgery) => +app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger logger) => { - if (!await antiforgery.IsRequestValidAsync(httpContext)) - return Results.BadRequest(new { error = "Invalid anti-forgery token" }); - if (string.IsNullOrEmpty(request.AccessToken)) + { + logger.LogWarning("Signin attempt without access token"); return Results.BadRequest(new { error = "AccessToken is required" }); + } // Validate the JWT server-side — extract claims from the validated token, not from client try @@ -157,7 +176,12 @@ app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest reque var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email)) + { + logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email); return Results.BadRequest(new { error = "Invalid token: missing user claims" }); + } + + logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId); // Re-build claims identity from validated token claims (never from client body) var claims = new List @@ -177,23 +201,25 @@ app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest reque var cookiePrincipal = new ClaimsPrincipal(identity); await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cookiePrincipal); + logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId); return Results.Ok(); } catch (SecurityTokenExpiredException) { + logger.LogWarning("Signin attempt with expired JWT"); return Results.Unauthorized(); } catch (Exception ex) { + logger.LogError(ex, "Signin failed — JWT validation error"); return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); } }); -app.MapPost("/_auth/signout", async (HttpContext httpContext, IAntiforgery antiforgery) => +app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => { - if (!await antiforgery.IsRequestValidAsync(httpContext)) - return Results.BadRequest(new { error = "Invalid anti-forgery token" }); - + var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)"; + logger.LogInformation("Signing out user {Email}", email); await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Ok(); }); diff --git a/src/Heimdall.Web/Services/AuthHelper.cs b/src/Heimdall.Web/Services/AuthHelper.cs index 55595aa..6efde04 100644 --- a/src/Heimdall.Web/Services/AuthHelper.cs +++ b/src/Heimdall.Web/Services/AuthHelper.cs @@ -6,9 +6,21 @@ namespace Heimdall.Web.Services; internal static class AuthHelper { /// Creates the middleware-level auth cookie via JS interop. - public static async Task SignInAsync(IJSRuntime jsRuntime, object user) + /// True if the sign-in HTTP call succeeded (2xx). + public static async Task SignInAsync(IJSRuntime jsRuntime, object user) { - await jsRuntime.InvokeVoidAsync("heimdallAuth.signIn", user); + try + { + var ok = await jsRuntime.InvokeAsync("heimdallAuth.signIn", user); + if (!ok) + Console.Error.WriteLine("[AuthHelper] SignInAsync: /_auth/signin returned non-2xx status"); + return ok; + } + catch (Exception ex) + { + Console.Error.WriteLine($"[AuthHelper] SignInAsync JS interop failed: {ex.Message}"); + return false; + } } /// Creates a sign-in payload object with the JWT access token.