diff --git a/src/Heimdall.Web/Components/App.razor b/src/Heimdall.Web/Components/App.razor index 52d051a..590a06b 100644 --- a/src/Heimdall.Web/Components/App.razor +++ b/src/Heimdall.Web/Components/App.razor @@ -18,6 +18,7 @@ + diff --git a/src/Heimdall.Web/Components/Layout/MainLayout.razor b/src/Heimdall.Web/Components/Layout/MainLayout.razor index c23ecfc..dd32bfe 100644 --- a/src/Heimdall.Web/Components/Layout/MainLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MainLayout.razor @@ -2,6 +2,7 @@ @inject AuthState Auth @inject NavigationManager Navigation @inject HeimdallAuthStateProvider AuthStateProvider +@inject IJSRuntime JsRuntime @@ -83,6 +84,7 @@ private async Task Logout() { await AuthStateProvider.NotifyLogoutAsync(); + await JsRuntime.InvokeVoidAsync("heimdallAuth.signOut"); Navigation.NavigateTo("/login", true); } } diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index 9d0ca43..7ee8a67 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -5,6 +5,7 @@ @inject NavigationManager Navigation @inject ISnackbar Snackbar @inject HeimdallAuthStateProvider AuthStateProvider +@inject IJSRuntime JsRuntime @using Microsoft.AspNetCore.WebUtilities @@ -73,7 +74,23 @@ _errorMessage = "Email ou mot de passe invalide"; return; } + + // Update Blazor-level auth state await AuthStateProvider.NotifyLoginAsync(result); + + // Create middleware-level auth cookie so the ASP.NET Core + // middleware recognizes the user on subsequent requests. + if (result.User is not null) + { + await JsRuntime.InvokeVoidAsync("heimdallAuth.signIn", new + { + id = result.User.Id.ToString(), + email = result.User.Email, + displayName = result.User.DisplayName, + roles = result.User.Roles + }); + } + 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 d4e8978..b223b30 100644 --- a/src/Heimdall.Web/Components/Pages/Register.razor +++ b/src/Heimdall.Web/Components/Pages/Register.razor @@ -5,6 +5,7 @@ @inject NavigationManager Navigation @inject ISnackbar Snackbar @inject HeimdallAuthStateProvider AuthStateProvider +@inject IJSRuntime JsRuntime @@ -55,7 +56,22 @@ _errorMessage = "Erreur lors de l'inscription"; return; } + + // Update Blazor-level auth state await AuthStateProvider.NotifyLoginAsync(result); + + // Create middleware-level auth cookie + if (result.User is not null) + { + await JsRuntime.InvokeVoidAsync("heimdallAuth.signIn", new + { + id = result.User.Id.ToString(), + email = result.User.Email, + displayName = result.User.DisplayName, + roles = result.User.Roles + }); + } + 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 959e433..2654579 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -1,6 +1,8 @@ using System.Security.Claims; using Heimdall.Web.Components; using Heimdall.Web.Services; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Components.Authorization; using MudBlazor.Services; @@ -22,11 +24,32 @@ builder.WebHost.UseSentry(options => builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); -// Auth for Blazor -builder.Services.AddScoped(); +// ── Authentication (Microsoft Identity pattern: cookie auth) ────── +// The app uses JWT auth via the Heimdall API at the application level. +// At the ASP.NET Core middleware level, we use cookie authentication +// to persist the user session across requests. +// The cookie is created after successful API login (see /_auth/signin). +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; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.ExpireTimeSpan = TimeSpan.FromDays(7); + options.SlidingExpiration = true; + }); + builder.Services.AddAuthorizationCore(); builder.Services.AddCascadingAuthenticationState(); +// Blazor auth state provider (reads JWT from ProtectedLocalStorage) +builder.Services.AddScoped(); + +// ── MudBlazor ───────────────────────────────────────────────────── builder.Services.AddMudServices(config => { config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; @@ -35,6 +58,7 @@ builder.Services.AddMudServices(config => config.SnackbarConfiguration.VisibleStateDuration = 4000; }); +// ── HTTP client for Heimdall API ────────────────────────────────── builder.Services.AddScoped(); var apiBaseUrl = builder.Configuration.GetValue("ApiBaseUrl") ?? Environment.GetEnvironmentVariable("API_BASE_URL") @@ -45,11 +69,12 @@ builder.Services.AddHttpClient("HeimdallApi", client => client.Timeout = TimeSpan.FromSeconds(30); }); -// Auth state +// Auth state (shared between services and components) builder.Services.AddScoped(); var app = builder.Build(); +// ── Middleware pipeline ──────────────────────────────────────────── if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); @@ -60,7 +85,54 @@ app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: app.UseHttpsRedirection(); app.UseAntiforgery(); app.MapStaticAssets(); + +app.UseAuthentication(); +app.UseAuthorization(); + app.MapRazorComponents() .AddInteractiveServerRenderMode(); +// ── Cookie auth endpoints (called from Blazor via JS fetch) ─────── +// /_auth/signin — Creates an authentication cookie after successful API login +// /_auth/signout — Clears the authentication cookie on logout + +app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request) => +{ + if (string.IsNullOrEmpty(request.Id) || string.IsNullOrEmpty(request.Email)) + return Results.BadRequest(new { error = "Id and Email are required" }); + + var claims = new List + { + new(ClaimTypes.NameIdentifier, request.Id), + new(ClaimTypes.Email, request.Email), + new(ClaimTypes.Name, request.DisplayName ?? request.Email), + }; + + if (request.Roles is not null) + { + foreach (var role in request.Roles) + claims.Add(new Claim(ClaimTypes.Role, role)); + } + + var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + var principal = new ClaimsPrincipal(identity); + + await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); + return Results.Ok(); +}); + +app.MapPost("/_auth/signout", async (HttpContext httpContext) => +{ + await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return Results.Ok(); +}); + app.Run(); + +// ─── DTO for the cookie sign-in request ─────────────────────────── + +internal sealed record SignInRequest( + string Id, + string Email, + string? DisplayName, + IList? Roles); diff --git a/src/Heimdall.Web/wwwroot/js/auth.js b/src/Heimdall.Web/wwwroot/js/auth.js new file mode 100644 index 0000000..3b162c5 --- /dev/null +++ b/src/Heimdall.Web/wwwroot/js/auth.js @@ -0,0 +1,31 @@ +// ── Cookie auth bridge ─────────────────────────────────────────── +// Called from Blazor via IJSRuntime after login/logout to sync the +// middleware-level auth cookie with the Blazor auth state. + +window.heimdallAuth = { + signIn: async function (data) { + try { + const response = await fetch('/_auth/signin', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + credentials: 'include' + }); + return response.ok; + } catch { + return false; + } + }, + + signOut: async function () { + try { + const response = await fetch('/_auth/signout', { + method: 'POST', + credentials: 'include' + }); + return response.ok; + } catch { + return false; + } + } +};