fix(web): add cookie authentication to fix IAuthenticationService missing error

This commit is contained in:
Arnaud Dartois committed 2026-07-18 20:59:38 +00:00
1 parent f5c4bcd5f0
commit 39f08e39ed
6 files changed
+142 -3

No files matched your search

+1
View File
@@ -18,6 +18,7 @@
<Routes />
<script src="@Assets["_framework/blazor.web.js"]"></script>
<script src="@Assets["_content/MudBlazor/MudBlazor.min.js"]"></script>
<script src="@Assets["js/auth.js"]"></script>
</body>
</html>
@@ -2,6 +2,7 @@
@inject AuthState Auth
@inject NavigationManager Navigation
@inject HeimdallAuthStateProvider AuthStateProvider
@inject IJSRuntime JsRuntime
<MudThemeProvider />
<MudDialogProvider />
@@ -83,6 +84,7 @@
private async Task Logout()
{
await AuthStateProvider.NotifyLogoutAsync();
await JsRuntime.InvokeVoidAsync("heimdallAuth.signOut");
Navigation.NavigateTo("/login", true);
}
}
@@ -5,6 +5,7 @@
@inject NavigationManager Navigation
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthStateProvider
@inject IJSRuntime JsRuntime
@using Microsoft.AspNetCore.WebUtilities
<MudContainer MaxWidth="MaxWidth.ExtraSmall" Class="mt-16">
@@ -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);
}
@@ -5,6 +5,7 @@
@inject NavigationManager Navigation
@inject ISnackbar Snackbar
@inject HeimdallAuthStateProvider AuthStateProvider
@inject IJSRuntime JsRuntime
<MudContainer MaxWidth="MaxWidth.ExtraSmall" Class="mt-16">
<MudPaper Elevation="5" Class="pa-8" Style="border-radius: 16px;">
@@ -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");
}
+75 -3
View File
@@ -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<AuthenticationStateProvider, HeimdallAuthStateProvider>();
// ── 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<AuthenticationStateProvider, HeimdallAuthStateProvider>();
// ── 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<HeimdallApiClient>();
var apiBaseUrl = builder.Configuration.GetValue<string>("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<AuthState>();
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<App>()
.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<Claim>
{
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<string>? Roles);
+31
View File
@@ -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;
}
}
};