2026-08-09 23:43:11 +02:00
|
|
|
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;
|
|
|
|
|
|
2026-08-10 00:09:22 +02:00
|
|
|
// 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}/";
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-09 23:43:11 +02:00
|
|
|
// 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;
|
2026-08-11 11:59:18 +02:00
|
|
|
private readonly AuthState _authState;
|
2026-08-09 23:43:11 +02:00
|
|
|
|
|
|
|
|
public SameOriginHttpMessageHandler(
|
|
|
|
|
IHttpContextAccessor httpContextAccessor,
|
|
|
|
|
IConfiguration configuration,
|
2026-08-11 11:59:18 +02:00
|
|
|
IServer server,
|
|
|
|
|
AuthState authState)
|
2026-08-09 23:43:11 +02:00
|
|
|
{
|
|
|
|
|
_httpContextAccessor = httpContextAccessor;
|
|
|
|
|
_configuration = configuration;
|
|
|
|
|
_server = server;
|
2026-08-11 11:59:18 +02:00
|
|
|
_authState = authState;
|
2026-08-09 23:43:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 08:32:41 +02:00
|
|
|
// 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);
|
|
|
|
|
}
|
2026-08-11 11:59:18 +02:00
|
|
|
// Circuit Blazor (HttpContext null) : le navigateur ne transmet pas le
|
|
|
|
|
// cookie au serveur par le circuit, et AccessToken peut être null quand
|
|
|
|
|
// le sessionStorage est vide (reload) — on réutilise alors le cookie
|
|
|
|
|
// capturé lors de la restauration SSR (AuthState.AuthCookie) pour que
|
|
|
|
|
// les appels API du circuit restent authentifiés (sinon 302 en boucle).
|
|
|
|
|
else if (http is null
|
|
|
|
|
&& request.Headers.Authorization is null
|
|
|
|
|
&& !request.Headers.Contains("Cookie")
|
|
|
|
|
&& !string.IsNullOrEmpty(_authState.AuthCookie))
|
|
|
|
|
{
|
|
|
|
|
request.Headers.TryAddWithoutValidation("Cookie",
|
|
|
|
|
$"{AuthState.AuthCookieName}={_authState.AuthCookie}");
|
|
|
|
|
}
|
2026-08-11 08:32:41 +02:00
|
|
|
|
2026-08-09 23:43:11 +02:00
|
|
|
return base.SendAsync(request, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
}
|