using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; namespace Heimdall.Web.Services; /// /// 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). /// public static class ApiBaseUrlResolver { /// Placeholder used when no explicit base URL is configured; the /// SameOriginHttpMessageHandler rewrites it to the request origin. public const string PlaceholderBase = "http://heimdall.local/"; /// True when an explicit base URL is configured (config or env). public static bool IsConfigured(IConfiguration configuration) => !string.IsNullOrWhiteSpace(ResolveConfigured(configuration)); /// Returns the explicitly configured URL, or null when unset. public static string? ResolveConfigured(IConfiguration configuration) => configuration.GetValue("ApiBaseUrl"); /// /// 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). /// public static string? ResolveOrigin(IHttpContextAccessor httpContextAccessor) { var http = httpContextAccessor.HttpContext; if (http is null) return null; return $"{http.Request.Scheme}://{http.Request.Host}"; } /// /// 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. /// public static string? ResolveFromServer(IServer server) { try { var addresses = server.Features.Get()?.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; } } /// /// 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. /// 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/"; } } /// /// DelegatingHandler that rewrites requests to the current request origin when /// no explicit ApiBaseUrl is configured. The named HttpClient is registered /// with 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. /// public class SameOriginHttpMessageHandler : DelegatingHandler { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IConfiguration _configuration; private readonly IServer _server; private readonly AuthState _authState; public SameOriginHttpMessageHandler( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, IServer server, AuthState authState) { _httpContextAccessor = httpContextAccessor; _configuration = configuration; _server = server; _authState = authState; } protected override Task 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); } // 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}"); } return base.SendAsync(request, cancellationToken); } }