using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; using Heimdall.Application.Auth.Services; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Components.Server; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; using Heimdall.Infrastructure.Security; namespace Heimdall.Web.Services; public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStateProvider { private readonly IServiceScopeFactory? _scopeFactory; private readonly ProtectedSessionStorage _storage; private readonly AuthState _authState; private readonly IHttpContextAccessor _httpContextAccessor; private bool _restoredFromStorage; private const string StorageKey = "heimdall_auth"; public HeimdallAuthStateProvider(ProtectedSessionStorage storage, AuthState authState, IHttpContextAccessor httpContextAccessor) : this(storage, authState, httpContextAccessor, null) { } public HeimdallAuthStateProvider( ProtectedSessionStorage storage, AuthState authState, IHttpContextAccessor httpContextAccessor, IServiceScopeFactory? scopeFactory) : base(NullLoggerFactory.Instance) { _scopeFactory = scopeFactory; _storage = storage; _authState = authState; _httpContextAccessor = httpContextAccessor; } protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1); protected override async Task ValidateAuthenticationStateAsync(AuthenticationState state, CancellationToken cancellationToken) { if (_scopeFactory is null) return false; await using var scope = _scopeFactory.CreateAsyncScope(); var valid = await AccountSessionPolicy.IsValidAsync(state.User, scope.ServiceProvider.GetRequiredService>(), scope.ServiceProvider.GetRequiredService(), cancellationToken); if (!valid) await NotifyLogoutAsync(); return valid; } public override async Task GetAuthenticationStateAsync() { // 1) Interactive circuit: the auth response is persisted in the browser // session storage after login. Read it when available. // // ⚠️ ProtectedSessionStorage (JS interop) is ONLY usable inside an // active circuit. During the initial server-side render (static/SSR // phase — HttpContext is present, no browser circuit yet) it throws // "JavaScript interop calls cannot be issued at this time" which // propagates up to the pages. So: circuit active (HttpContext null) // → read storage; otherwise → cookie fallback only. if (_httpContextAccessor.HttpContext is null) { try { var result = await _storage.GetAsync(StorageKey); if (result.Success && result.Value is not null) { var authResponse = result.Value; var state = CreateAuthenticationState(authResponse); if (_scopeFactory is not null && !await ValidateAuthenticationStateAsync(state, CancellationToken.None)) return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); _authState.Login(authResponse); if (!_restoredFromStorage) { _restoredFromStorage = true; SetAuthenticationState(Task.FromResult(state)); } return state; } } catch { // ProtectedBrowserStorage throws during SSR/prerender (no browser). } } // 2) SSR / prerender / page reload: fall back to the middleware cookie // principal (populated by /_auth/signin). This is what makes // full page navigations (F5, direct URL, links) work after login. var http = _httpContextAccessor.HttpContext; 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); } return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } public virtual async Task NotifyLoginAsync(AuthResponse response) { // Guard: JS interop unavailable outside an active circuit. When called // during static render, persist state in-memory only; the cookie is // created separately by AuthHelper.SignInAsync. if (_httpContextAccessor.HttpContext is null) { await _storage.SetAsync(StorageKey, response); } _authState.Login(response); NotifyAuthenticationStateChanged(Task.FromResult(CreateAuthenticationState(response))); } public virtual async Task NotifyLogoutAsync() { _authState.Logout(); if (_httpContextAccessor.HttpContext is null) { try { await _storage.DeleteAsync(StorageKey); } catch (Microsoft.JSInterop.JSDisconnectedException) { } catch (InvalidOperationException) { } // Revalidation may run while the circuit is disconnected. } NotifyAuthenticationStateChanged( Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())))); } private static AuthenticationState CreateAuthenticationState(AuthResponse response) { if (response.User is null) return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); var claims = new List { new(ClaimTypes.NameIdentifier, response.User.Id.ToString()), new(ClaimTypes.Name, response.User.DisplayName), new(ClaimTypes.Email, response.User.Email), new(ClaimTypes.AuthenticationMethod, "Bearer") }; if (new JwtSecurityTokenHandler().CanReadToken(response.AccessToken)) { var token = new JwtSecurityTokenHandler().ReadJwtToken(response.AccessToken); foreach (var claim in token.Claims.Where(c => c.Type == AccountSessionPolicy.StampClaim || c.Type == AccountSessionPolicy.StartedClaim)) claims.Add(claim); } foreach (var role in response.User.Roles ?? []) claims.Add(new Claim(ClaimTypes.Role, role)); // Map roles → permissions via the AppPermissions dictionary (same as AuthService) var permissions = response.User.Roles? .SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : []) .ToList() ?? []; foreach (var permission in permissions) claims.Add(new Claim("permission", permission)); var identity = new ClaimsIdentity(claims, "Bearer"); return new AuthenticationState(new ClaimsPrincipal(identity)); } }