From 2317e3d50cc3a0bef8dd502eba057a2e07765f51 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 27 Feb 2019 18:52:11 +0900 Subject: [PATCH] Make sure we rewrite the request scheme --- BTCPayServer/BTCPayServer.csproj | 2 +- BTCPayServer/Hosting/BTCpayMiddleware.cs | 53 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/BTCPayServer/BTCPayServer.csproj b/BTCPayServer/BTCPayServer.csproj index b2fa9a21f..40306e292 100644 --- a/BTCPayServer/BTCPayServer.csproj +++ b/BTCPayServer/BTCPayServer.csproj @@ -2,7 +2,7 @@ Exe netcoreapp2.1 - 1.0.3.66 + 1.0.3.67 NU1701,CA1816,CA1308,CA1810,CA2208 diff --git a/BTCPayServer/Hosting/BTCpayMiddleware.cs b/BTCPayServer/Hosting/BTCpayMiddleware.cs index b3ff43b08..82b03040f 100644 --- a/BTCPayServer/Hosting/BTCpayMiddleware.cs +++ b/BTCPayServer/Hosting/BTCpayMiddleware.cs @@ -32,6 +32,8 @@ namespace BTCPayServer.Hosting public async Task Invoke(HttpContext httpContext) { + RewriteHostIfNeeded(httpContext); + try { var bitpayAuth = GetBitpayAuth(httpContext, out bool isBitpayAuth); @@ -123,6 +125,57 @@ namespace BTCPayServer.Hosting return false; } + private void RewriteHostIfNeeded(HttpContext httpContext) + { + string reverseProxyScheme = null; + if (httpContext.Request.Headers.TryGetValue("X-Forwarded-Proto", out StringValues proto)) + { + var scheme = proto.SingleOrDefault(); + if (scheme != null) + { + reverseProxyScheme = scheme; + } + } + + ushort? reverseProxyPort = null; + if (httpContext.Request.Headers.TryGetValue("X-Forwarded-Port", out StringValues port)) + { + var portString = port.SingleOrDefault(); + if (portString != null && ushort.TryParse(portString, out ushort pp)) + { + reverseProxyPort = pp; + } + } + + // NGINX pass X-Forwarded-Proto and X-Forwarded-Port, so let's use that to have better guess of the real domain + + ushort? p = null; + if (reverseProxyScheme != null) + { + httpContext.Request.Scheme = reverseProxyScheme; + if (reverseProxyScheme == "http") + p = 80; + if (reverseProxyScheme == "https") + p = 443; + } + + if (reverseProxyPort != null) + { + p = reverseProxyPort.Value; + } + + if (p.HasValue) + { + bool isDefault = httpContext.Request.Scheme == "http" && p.Value == 80; + isDefault |= httpContext.Request.Scheme == "https" && p.Value == 443; + if (isDefault) + httpContext.Request.Host = new HostString(httpContext.Request.Host.Host); + else + httpContext.Request.Host = new HostString(httpContext.Request.Host.Host, p.Value); + } + + } + private static async Task HandleBitpayHttpException(HttpContext httpContext, BitpayHttpException ex) { httpContext.Response.StatusCode = ex.StatusCode;