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

164 lines
7.2 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
namespace Heimdall.Web.Services;
/// <summary>
/// Resolves the effective API base URL for browser-facing HTTP calls.
/// Heimdall is a Blazor Server monolith — the UI and the REST API run in the
/// same process — so unless an explicit ApiBaseUrl is configured (e.g. an
/// external API), calls should target the SAME origin the browser is using.
/// The old hardcoded "http://localhost:8080" default broke the UI whenever the
/// app was not running inside the Docker container (dev, E2E, bare metal).
/// </summary>
public static class ApiBaseUrlResolver
{
/// <summary>Placeholder used when no explicit base URL is configured; the
/// SameOriginHttpMessageHandler rewrites it to the request origin.</summary>
public const string PlaceholderBase = "http://heimdall.local/";
/// <summary>True when an explicit base URL is configured (config or env).</summary>
public static bool IsConfigured(IConfiguration configuration) =>
!string.IsNullOrWhiteSpace(ResolveConfigured(configuration));
/// <summary>Returns the explicitly configured URL, or null when unset.</summary>
public static string? ResolveConfigured(IConfiguration configuration) =>
configuration.GetValue<string>("ApiBaseUrl")
?? Environment.GetEnvironmentVariable("API_BASE_URL");
/// <summary>
/// Effective origin for the current request (scheme://host). Returns null
/// when no HttpContext is available — which is common in Blazor Server
/// circuits after hydration (component-triggered calls have no request).
/// </summary>
public static string? ResolveOrigin(IHttpContextAccessor httpContextAccessor)
{
var http = httpContextAccessor.HttpContext;
if (http is null)
return null;
return $"{http.Request.Scheme}://{http.Request.Host}";
}
/// <summary>
/// Resolves the origin from the Kestrel server's bound addresses. Used as a
/// fallback when no HttpContext is available (Blazor Server circuit calls).
/// Returns null when the server exposes no usable HTTP address.
/// </summary>
public static string? ResolveFromServer(IServer server)
{
try
{
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses;
if (addresses is null)
return null;
var httpAddress = addresses.FirstOrDefault(a =>
a.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
&& !a.Contains("0.0.0.0", StringComparison.OrdinalIgnoreCase)
&& !a.Contains("[::]", StringComparison.OrdinalIgnoreCase))
?? addresses.FirstOrDefault(a => a.StartsWith("http://", StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrWhiteSpace(httpAddress))
return null;
// Wildcard binds (0.0.0.0 / [::]) cannot be dialed by an HttpClient —
// replace the host with loopback, keeping the bound port.
if (httpAddress.Contains("0.0.0.0", StringComparison.OrdinalIgnoreCase)
|| httpAddress.Contains("[::]", StringComparison.OrdinalIgnoreCase))
{
var port = new Uri(httpAddress).Port;
httpAddress = $"http://localhost:{port}/";
}
// http://127.0.0.1:5000 -> http://127.0.0.1:5000/
return httpAddress.EndsWith('/') ? httpAddress : httpAddress + "/";
}
catch
{
return null;
}
}
/// <summary>
/// Absolute base URL for out-of-band calls (e.g. token refresh): explicit
/// config when set, otherwise the current request origin (monolith), with a
/// loopback fallback when no request context is available.
/// </summary>
public static string Resolve(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
{
var configured = ResolveConfigured(configuration);
if (!string.IsNullOrWhiteSpace(configured))
return configured.EndsWith('/') ? configured : configured + "/";
var origin = ResolveOrigin(httpContextAccessor);
if (!string.IsNullOrWhiteSpace(origin))
return origin.EndsWith('/') ? origin : origin + "/";
return "http://localhost/";
}
}
/// <summary>
/// DelegatingHandler that rewrites requests to the current request origin when
/// no explicit ApiBaseUrl is configured. The named HttpClient is registered
/// with <see cref="ApiBaseUrlResolver.PlaceholderBase"/> as BaseAddress (so
/// relative paths resolve) and this handler swaps the placeholder host for the
/// real origin before the call leaves the process.
///
/// In Blazor Server, calls triggered by component code (OnInitializedAsync,
/// event handlers) run inside the circuit WITHOUT an HttpContext, so the
/// handler falls back to the server's bound addresses.
/// </summary>
public class SameOriginHttpMessageHandler : DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private readonly IServer _server;
public SameOriginHttpMessageHandler(
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration,
IServer server)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_server = server;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!ApiBaseUrlResolver.IsConfigured(_configuration)
&& request.RequestUri is not null
&& request.RequestUri.OriginalString.StartsWith(
ApiBaseUrlResolver.PlaceholderBase, StringComparison.OrdinalIgnoreCase))
{
var origin = ApiBaseUrlResolver.ResolveOrigin(_httpContextAccessor)
?? ApiBaseUrlResolver.ResolveFromServer(_server);
if (!string.IsNullOrWhiteSpace(origin))
{
var path = request.RequestUri.OriginalString[ApiBaseUrlResolver.PlaceholderBase.Length..];
request.RequestUri = new Uri($"{origin.TrimEnd('/')}/{path}");
}
}
// Au premier rendu (SSR / F5), AuthState n'a pas de JWT (peuplé depuis le
// cookie) et le HttpClient serveur n'envoie pas le cookie du navigateur.
// On propage le cookie d'authentification du HttpContext courant pour que
// les appels API internes soient authentifiés pendant le rendu initial.
// Une fois le circuit actif, AuthState.AccessToken est présent et le
// Bearer (posé par HeimdallApiClient) prend le relais.
var http = _httpContextAccessor.HttpContext;
if (http is not null
&& http.User?.Identity?.IsAuthenticated == true
&& request.Headers.Authorization is null
&& !request.Headers.Contains("Cookie"))
{
var cookie = http.Request.Headers.Cookie.ToString();
if (!string.IsNullOrWhiteSpace(cookie))
request.Headers.TryAddWithoutValidation("Cookie", cookie);
}
return base.SendAsync(request, cancellationToken);
}
}