Files
Heimdall/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs
T

125 lines
5.0 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Heimdall.Infrastructure.Security;
namespace Heimdall.Web.Services;
public class HeimdallAuthStateProvider : AuthenticationStateProvider
{
private readonly ProtectedSessionStorage _storage;
private readonly AuthState _authState;
private readonly IHttpContextAccessor _httpContextAccessor;
private const string StorageKey = "heimdall_auth";
public HeimdallAuthStateProvider(
ProtectedSessionStorage storage,
AuthState authState,
IHttpContextAccessor httpContextAccessor)
{
_storage = storage;
_authState = authState;
_httpContextAccessor = httpContextAccessor;
}
public override async Task<AuthenticationState> 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<AuthResponse>(StorageKey);
if (result.Success && result.Value is not null)
{
var authResponse = result.Value;
_authState.Login(authResponse);
return CreateAuthenticationState(authResponse);
}
}
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()
{
if (_httpContextAccessor.HttpContext is null)
{
await _storage.DeleteAsync(StorageKey);
}
_authState.Logout();
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<Claim>
{
new(ClaimTypes.NameIdentifier, response.User.Id.ToString()),
new(ClaimTypes.Name, response.User.DisplayName),
new(ClaimTypes.Email, response.User.Email),
new(ClaimTypes.AuthenticationMethod, "Bearer")
};
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));
}
}