using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using Microsoft.Extensions.Configuration; namespace Heimdall.Web.Services; /// /// 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. /// 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 }; /// Prevents concurrent refresh storms when multiple requests fail at once. 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 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 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(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 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; } }