fix(web): handle login cookie creation failure
- Remove redundant antiforgery check from /_auth/signin and /_auth/signout (JWT validation is sufficient security; antiforgery tokens fail silently because the JS caller never includes one) - Add ILogger structured logging to both endpoints - Make AuthHelper.SignInAsync return bool so Blazor pages can detect failure - Show user-friendly error messages in Login.razor and Register.razor when cookie creation fails
This commit is contained in:
1 parent
c8c93e3d87
commit
252724a2fd
4 files changed
+65
-13
No files matched your search
@@ -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<App>()
|
||||
.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<AppDbContext>();
|
||||
_ = 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<Program> 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<Claim>
|
||||
@@ -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<Program> 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();
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user