Anomalies corrigées : - MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur l'ouverture de menus/popovers (dashboard jamais rendu après login) - AddIdentity redéfinissait le schéma par défaut sur Identity.Application alors que /_auth/signin signait avec Cookies → cookie posé mais jamais validé, tout rechargement de page redirigeait vers /login. Forçage du schéma par défaut sur Cookies + schémas JwtBearer explicites sur les endpoints API d'AuthController et SettingsController - Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée → 500 à l'appel. Ajoutée (RequireRole Admin) - HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur : pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé → pages protégées redirigées vers /login. Fallback cookie ajouté - SameOriginHttpMessageHandler : résolution de l'origine via IServerAddressesFeature quand IHttpContextAccessor est null (circuit Blazor post-hydratation) au lieu de heimdall.local → DNS cassé - UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400 à l'édition. Accepte désormais auto (case-insensitive) Tests : - E2E Playwright complets (login/logout/register/user management) : 33/33 - Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du valueType, bootstrap admin via /register auto-admin, header X-API-Key, /proc/meminfo optionnel pour les LXC restreints) - Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
135 lines
4.8 KiB
C#
135 lines
4.8 KiB
C#
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace Heimdall.Web.Services;
|
|
|
|
/// <summary>
|
|
/// DelegatingHandler that intercepts 401 responses and automatically tries
|
|
/// to refresh the access token using the stored refresh token.
|
|
/// If refresh fails, the user is logged out.
|
|
/// </summary>
|
|
public class TokenRefreshHandler : DelegatingHandler
|
|
{
|
|
private readonly AuthState _authState;
|
|
private readonly HeimdallAuthStateProvider _authStateProvider;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
private readonly IConfiguration _configuration;
|
|
private static readonly JsonSerializerOptions Json = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
};
|
|
|
|
/// <summary>Prevents concurrent refresh storms when multiple requests fail at once.</summary>
|
|
private static readonly SemaphoreSlim _refreshLock = new(1, 1);
|
|
|
|
public TokenRefreshHandler(
|
|
AuthState authState,
|
|
HeimdallAuthStateProvider authStateProvider,
|
|
IHttpContextAccessor httpContextAccessor,
|
|
IConfiguration configuration)
|
|
{
|
|
_authState = authState;
|
|
_authStateProvider = authStateProvider;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
_configuration = configuration;
|
|
}
|
|
|
|
protected override async Task<HttpResponseMessage> SendAsync(
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
// Clone the request so we can retry it
|
|
var response = await base.SendAsync(request, cancellationToken);
|
|
|
|
// Only intercept 401 responses for the Heimdall API
|
|
if (response.StatusCode != System.Net.HttpStatusCode.Unauthorized
|
|
|| request.RequestUri?.LocalPath.StartsWith("/api/auth/", StringComparison.Ordinal) == true)
|
|
{
|
|
return response;
|
|
}
|
|
|
|
// Try to refresh the token
|
|
var refreshed = await TryRefreshTokenAsync(cancellationToken);
|
|
if (!refreshed)
|
|
{
|
|
// Refresh failed — logout user
|
|
await _authStateProvider.NotifyLogoutAsync();
|
|
return response;
|
|
}
|
|
|
|
// Retry the original request with the new access token
|
|
var retryRequest = await CloneHttpRequestMessageAsync(request);
|
|
retryRequest.Headers.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
|
|
|
|
response.Dispose();
|
|
return await base.SendAsync(retryRequest, cancellationToken);
|
|
}
|
|
|
|
private async Task<bool> TryRefreshTokenAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (string.IsNullOrEmpty(_authState.RefreshToken))
|
|
return false;
|
|
|
|
await _refreshLock.WaitAsync(cancellationToken);
|
|
try
|
|
{
|
|
// Double-check: another thread might have refreshed already
|
|
if (!string.IsNullOrEmpty(_authState.AccessToken))
|
|
return true;
|
|
|
|
// Create a raw HttpClient (NOT the "HeimdallApi" named client which
|
|
// includes this handler — would cause an infinite loop).
|
|
var baseUrl = ApiBaseUrlResolver.Resolve(_httpContextAccessor, _configuration);
|
|
using var rawClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
|
var response = await rawClient.PostAsJsonAsync(
|
|
"api/auth/refresh",
|
|
new { refreshToken = _authState.RefreshToken },
|
|
cancellationToken);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
return false;
|
|
|
|
var result = await response.Content
|
|
.ReadFromJsonAsync<AuthResponse>(Json, cancellationToken);
|
|
|
|
if (result is null || string.IsNullOrEmpty(result.AccessToken))
|
|
return false;
|
|
|
|
// Update auth state with the new tokens
|
|
await _authStateProvider.NotifyLoginAsync(result);
|
|
return true;
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
finally
|
|
{
|
|
_refreshLock.Release();
|
|
}
|
|
}
|
|
|
|
private static async Task<HttpRequestMessage> CloneHttpRequestMessageAsync(HttpRequestMessage request)
|
|
{
|
|
var clone = new HttpRequestMessage(request.Method, request.RequestUri);
|
|
if (request.Content is not null)
|
|
{
|
|
var contentBytes = await request.Content.ReadAsByteArrayAsync();
|
|
clone.Content = new ByteArrayContent(contentBytes);
|
|
if (request.Content.Headers.ContentType is not null)
|
|
clone.Content.Headers.ContentType = request.Content.Headers.ContentType;
|
|
}
|
|
|
|
foreach (var (key, value) in request.Headers)
|
|
clone.Headers.TryAddWithoutValidation(key, value);
|
|
|
|
foreach (var (key, value) in request.Options)
|
|
clone.Options.TryAdd(key, value);
|
|
|
|
return clone;
|
|
}
|
|
}
|