2026-07-21 08:57:53 +00:00
|
|
|
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;
|
2026-08-09 23:43:11 +02:00
|
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
|
private readonly IConfiguration _configuration;
|
2026-07-21 08:57:53 +00:00
|
|
|
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,
|
2026-08-09 23:43:11 +02:00
|
|
|
IHttpContextAccessor httpContextAccessor,
|
2026-07-21 08:57:53 +00:00
|
|
|
IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
_authState = authState;
|
|
|
|
|
_authStateProvider = authStateProvider;
|
2026-08-09 23:43:11 +02:00
|
|
|
_httpContextAccessor = httpContextAccessor;
|
|
|
|
|
_configuration = configuration;
|
2026-07-21 08:57:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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).
|
2026-08-09 23:43:11 +02:00
|
|
|
var baseUrl = ApiBaseUrlResolver.Resolve(_httpContextAccessor, _configuration);
|
2026-07-27 18:43:25 +00:00
|
|
|
using var rawClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
2026-07-21 08:57:53 +00:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|