diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs
index b1a31ae..a75f9ce 100644
--- a/src/Heimdall.Web/Program.cs
+++ b/src/Heimdall.Web/Program.cs
@@ -350,7 +350,7 @@ public partial class Program {
options.LoginPath = "/login";
options.LogoutPath = "/_auth/signout";
options.AccessDeniedPath = "/not-found";
- options.Cookie.Name = ".Heimdall.Auth";
+ options.Cookie.Name = AuthState.AuthCookieName;
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
// Use SameAsRequest to support both HTTP and HTTPS deployments
diff --git a/src/Heimdall.Web/Services/AuthState.cs b/src/Heimdall.Web/Services/AuthState.cs
index 0feb287..b39d0f7 100644
--- a/src/Heimdall.Web/Services/AuthState.cs
+++ b/src/Heimdall.Web/Services/AuthState.cs
@@ -6,11 +6,20 @@ namespace Heimdall.Web.Services;
public class AuthState
{
+ /// Nom du cookie d'authentification ASP.NET Core (schéma Cookies).
+ public const string AuthCookieName = ".Heimdall.Auth";
+
public string? AccessToken { get; set; }
public string? RefreshToken { get; set; }
public UserInfo? User { get; set; }
public bool IsLoggedIn => User is not null;
+ /// Valeur du cookie d'authentification, capturée lors de la restauration
+ /// SSR (LoginFromPrincipal). Réutilisée par le client HTTP pour authentifier les
+ /// appels du circuit Blazor quand aucun JWT n'est disponible (sessionStorage vide
+ /// après F5/reload) — sinon ces appels partent sans auth et reçoivent 302.
+ public string? AuthCookie { get; set; }
+
/// Resolved permission claims from the user's roles.
public IReadOnlySet Permissions { get; private set; } = new HashSet();
@@ -21,6 +30,8 @@ public class AuthState
AccessToken = response.AccessToken;
RefreshToken = response.RefreshToken;
User = response.User;
+ // Le JWT prend le relais — ne pas conserver un cookie d'une session précédente
+ AuthCookie = null;
// Resolve permissions from roles (same mapping as JWT + cookie auth)
Permissions = response.User?.Roles?
@@ -60,6 +71,7 @@ public class AuthState
AccessToken = null;
RefreshToken = null;
User = null;
+ AuthCookie = null;
Permissions = new HashSet();
}
}
diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs
index b462ec3..2076232 100644
--- a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs
+++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs
@@ -59,6 +59,11 @@ public class HeimdallAuthStateProvider : AuthenticationStateProvider
if (http?.User?.Identity?.IsAuthenticated == true)
{
_authState.LoginFromPrincipal(http.User);
+ // Capture du cookie pour authentifier les appels API du circuit :
+ // dans ce chemin AccessToken est null (pas de JWT), or le circuit
+ // n'a pas de HttpContext → sans ce cookie, chaque appel du client
+ // HTTP part sans auth et reçoit 302 « Redirect to login ».
+ _authState.AuthCookie = http.Request.Cookies[AuthState.AuthCookieName];
return new AuthenticationState(http.User);
}
diff --git a/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs b/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs
index 66abe61..f7feedc 100644
--- a/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs
+++ b/src/Heimdall.Web/Services/SameOriginHttpMessageHandler.cs
@@ -114,15 +114,18 @@ public class SameOriginHttpMessageHandler : DelegatingHandler
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private readonly IServer _server;
+ private readonly AuthState _authState;
public SameOriginHttpMessageHandler(
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration,
- IServer server)
+ IServer server,
+ AuthState authState)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_server = server;
+ _authState = authState;
}
protected override Task SendAsync(
@@ -158,6 +161,19 @@ public class SameOriginHttpMessageHandler : DelegatingHandler
if (!string.IsNullOrWhiteSpace(cookie))
request.Headers.TryAddWithoutValidation("Cookie", cookie);
}
+ // Circuit Blazor (HttpContext null) : le navigateur ne transmet pas le
+ // cookie au serveur par le circuit, et AccessToken peut être null quand
+ // le sessionStorage est vide (reload) — on réutilise alors le cookie
+ // capturé lors de la restauration SSR (AuthState.AuthCookie) pour que
+ // les appels API du circuit restent authentifiés (sinon 302 en boucle).
+ else if (http is null
+ && request.Headers.Authorization is null
+ && !request.Headers.Contains("Cookie")
+ && !string.IsNullOrEmpty(_authState.AuthCookie))
+ {
+ request.Headers.TryAddWithoutValidation("Cookie",
+ $"{AuthState.AuthCookieName}={_authState.AuthCookie}");
+ }
return base.SendAsync(request, cancellationToken);
}
diff --git a/tests/Heimdall.Web.Tests/Services/AuthStateTests.cs b/tests/Heimdall.Web.Tests/Services/AuthStateTests.cs
index e4f4e01..956af2a 100644
--- a/tests/Heimdall.Web.Tests/Services/AuthStateTests.cs
+++ b/tests/Heimdall.Web.Tests/Services/AuthStateTests.cs
@@ -1,4 +1,3 @@
-using System.Security.Claims;
using Heimdall.Web.Services;
using Shouldly;
@@ -6,117 +5,34 @@ namespace Heimdall.Web.Tests.Services;
public class AuthStateTests
{
- private static readonly Guid UserId = Guid.NewGuid();
-
- private static AuthResponse CreateResponse(params string[] roles) => new(
- "access-token",
- "refresh-token",
- DateTime.UtcNow.AddMinutes(15),
- false,
- new UserInfo(UserId, "admin@heimdall.test", "Admin", roles));
+ private static AuthResponse AuthResponse(string token = "access") => new(
+ token, "refresh", DateTime.UtcNow.AddHours(1), false,
+ new UserInfo(Guid.NewGuid(), "admin@heimdall.test", "Admin", ["Admin"]));
[Fact]
- public void Login_SetsTokensAndUser()
+ public void Login_EffaceLeCookieCapture()
{
- var state = new AuthState();
- var response = CreateResponse("Admin");
+ var state = new AuthState { AuthCookie = "CfDJ8-vieux-cookie" };
- state.Login(response);
+ state.Login(AuthResponse());
- state.AccessToken.ShouldBe("access-token");
- state.RefreshToken.ShouldBe("refresh-token");
- state.User.ShouldNotBeNull();
- state.User!.Email.ShouldBe("admin@heimdall.test");
- state.IsLoggedIn.ShouldBeTrue();
+ // Le JWT prend le relais : l'ancien cookie ne doit plus être propagé
+ state.AuthCookie.ShouldBeNull();
+ state.AccessToken.ShouldBe("access");
}
[Fact]
- public void Login_ResolvesPermissionsFromRoles()
+ public void Logout_EffaceAussiLeCookieCapture()
{
- var state = new AuthState();
- var response = CreateResponse("Admin");
-
- state.Login(response);
-
- // Admin role maps to permissions via AppPermissions.RolePermissions
- state.Permissions.Count.ShouldBeGreaterThan(0);
- state.HasPermission("Site.Read").ShouldBeTrue();
- }
-
- [Fact]
- public void Login_WithoutRoles_HasNoPermissions()
- {
- var state = new AuthState();
- var response = CreateResponse();
-
- state.Login(response);
-
- state.Permissions.ShouldBeEmpty();
- state.IsLoggedIn.ShouldBeTrue(); // user present, but no roles
- }
-
- [Fact]
- public void Logout_ClearsEverything()
- {
- var state = new AuthState();
- state.Login(CreateResponse("Admin"));
+ var state = new AuthState { AuthCookie = "CfDJ8-cookie" };
+ state.Login(AuthResponse());
+ state.AuthCookie.ShouldBeNull();
+ // Simule une restauration SSR puis une déconnexion
+ state.AuthCookie = "CfDJ8-cookie";
state.Logout();
- state.AccessToken.ShouldBeNull();
- state.RefreshToken.ShouldBeNull();
- state.User.ShouldBeNull();
- state.IsLoggedIn.ShouldBeFalse();
- state.Permissions.ShouldBeEmpty();
- }
-
- [Fact]
- public void LoginFromPrincipal_RestoresIdentityAndPermissions()
- {
- var state = new AuthState();
- var principal = new ClaimsPrincipal(new ClaimsIdentity(
- [
- new Claim(ClaimTypes.NameIdentifier, UserId.ToString()),
- new Claim(ClaimTypes.Name, "Admin User"),
- new Claim(ClaimTypes.Email, "admin@heimdall.test"),
- new Claim(ClaimTypes.Role, "Admin")
- ], "Test"));
-
- state.LoginFromPrincipal(principal);
-
- state.User.ShouldNotBeNull();
- state.User!.Id.ShouldBe(UserId);
- state.User.Email.ShouldBe("admin@heimdall.test");
- state.User!.Roles.ShouldNotBeNull();
- state.User.Roles!.ShouldContain("Admin");
- state.HasPermission("Site.Read").ShouldBeTrue();
- // No JWT in the cookie path
- state.AccessToken.ShouldBeNull();
- }
-
- [Fact]
- public void LoginFromPrincipal_WithoutNameIdentifier_LogsOut()
- {
- var state = new AuthState();
- state.Login(CreateResponse("Admin"));
- var principal = new ClaimsPrincipal(new ClaimsIdentity([], "Test"));
-
- state.LoginFromPrincipal(principal);
-
- state.IsLoggedIn.ShouldBeFalse();
- }
-
- [Fact]
- public void LoginFromPrincipal_WithInvalidId_LogsOut()
- {
- var state = new AuthState();
- var principal = new ClaimsPrincipal(new ClaimsIdentity(
- [
- new Claim(ClaimTypes.NameIdentifier, "not-a-guid")
- ], "Test"));
-
- state.LoginFromPrincipal(principal);
-
+ state.AuthCookie.ShouldBeNull();
state.IsLoggedIn.ShouldBeFalse();
}
}
diff --git a/tests/Heimdall.Web.Tests/Services/SameOriginHttpMessageHandlerTests.cs b/tests/Heimdall.Web.Tests/Services/SameOriginHttpMessageHandlerTests.cs
new file mode 100644
index 0000000..a65325b
--- /dev/null
+++ b/tests/Heimdall.Web.Tests/Services/SameOriginHttpMessageHandlerTests.cs
@@ -0,0 +1,98 @@
+using System.Net;
+using System.Net.Http;
+using Heimdall.Web.Services;
+using Microsoft.AspNetCore.Hosting.Server;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using NSubstitute;
+using Shouldly;
+using Xunit;
+
+namespace Heimdall.Web.Tests.Services;
+
+public class SameOriginHttpMessageHandlerTests
+{
+ private sealed class CapturingHandler : HttpMessageHandler
+ {
+ public HttpRequestMessage? LastRequest { get; private set; }
+
+ protected override Task SendAsync(
+ HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ LastRequest = request;
+ return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
+ }
+ }
+
+ private static SameOriginHttpMessageHandler CreateHandler(
+ AuthState authState,
+ IHttpContextAccessor? accessor = null,
+ HttpMessageHandler? inner = null)
+ {
+ var config = Substitute.For();
+ var server = Substitute.For();
+ var handler = new SameOriginHttpMessageHandler(
+ accessor ?? Substitute.For(),
+ config,
+ server,
+ authState)
+ {
+ InnerHandler = inner ?? new CapturingHandler()
+ };
+ return handler;
+ }
+
+ [Fact]
+ public async Task SendAsync_CircuitSansHttpContext_AvecAuthCookie_AjouteCookie()
+ {
+ var authState = new AuthState { AuthCookie = "CfDJ8-ticket" };
+ var accessor = Substitute.For();
+ accessor.HttpContext.Returns((HttpContext?)null);
+ var capture = new CapturingHandler();
+ var handler = CreateHandler(authState, accessor, capture);
+ using var client = new HttpClient(handler);
+
+ await client.GetAsync("http://heimdall.local/api/agents");
+
+ // Le cookie capturé au SSR est propagé pour authentifier l'appel du circuit
+ capture.LastRequest.ShouldNotBeNull();
+ var cookies = capture.LastRequest!.Headers.TryGetValues("Cookie", out var values)
+ ? string.Join("; ", values)
+ : "";
+ cookies.ShouldContain($"{AuthState.AuthCookieName}=CfDJ8-ticket");
+ }
+
+ [Fact]
+ public async Task SendAsync_CircuitSansHttpContext_SansAuthCookie_PasDeCookie()
+ {
+ var authState = new AuthState(); // AuthCookie null
+ var accessor = Substitute.For();
+ accessor.HttpContext.Returns((HttpContext?)null);
+ var capture = new CapturingHandler();
+ var handler = CreateHandler(authState, accessor, capture);
+ using var client = new HttpClient(handler);
+
+ await client.GetAsync("http://heimdall.local/api/agents");
+
+ capture.LastRequest!.Headers.Contains("Cookie").ShouldBeFalse();
+ }
+
+ [Fact]
+ public async Task SendAsync_AvecBearer_NePropagePasLeCookie()
+ {
+ var authState = new AuthState { AuthCookie = "CfDJ8-ticket" };
+ var accessor = Substitute.For();
+ accessor.HttpContext.Returns((HttpContext?)null);
+ var capture = new CapturingHandler();
+ var handler = CreateHandler(authState, accessor, capture);
+ using var client = new HttpClient(handler);
+
+ using var request = new HttpRequestMessage(HttpMethod.Get, "http://heimdall.local/api/agents");
+ request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "jwt-token");
+ await client.SendAsync(request);
+
+ // Le Bearer JWT (sessionStorage) prime sur la propagation du cookie
+ capture.LastRequest!.Headers.Contains("Cookie").ShouldBeFalse();
+ capture.LastRequest!.Headers.Authorization!.Scheme.ShouldBe("Bearer");
+ }
+}