From f2ee766b092a9a8aaa76856726e13d52e0631611 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Mon, 16 Jan 2023 13:28:03 +0500 Subject: [PATCH] identity: get correct remote address in case of auth failure --- .../Extensions/HttpContextExtensions.cs | 29 +++++++++++++++++-- Streetwriters.Identity/Startup.cs | 2 +- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/Streetwriters.Identity/Extensions/HttpContextExtensions.cs b/Streetwriters.Identity/Extensions/HttpContextExtensions.cs index a35bafc..1059943 100644 --- a/Streetwriters.Identity/Extensions/HttpContextExtensions.cs +++ b/Streetwriters.Identity/Extensions/HttpContextExtensions.cs @@ -18,6 +18,8 @@ along with this program. If not, see . */ using System; +using System.Linq; +using System.Net; using System.Text; using Ng.Services; @@ -25,18 +27,39 @@ namespace Microsoft.AspNetCore.Http { public static class HttpContextExtensions { + /// + /// Get remote ip address, optionally allowing for x-forwarded-for header check + /// + /// Http context + /// Whether to allow x-forwarded-for header check + /// IPAddress + public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true) + { + if (allowForwarded) + { + // if you are allowing these forward headers, please ensure you are restricting context.Connection.RemoteIpAddress + // to cloud flare ips: https://www.cloudflare.com/ips/ + string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault()); + if (IPAddress.TryParse(header, out IPAddress ip)) + { + return ip; + } + } + return context.Connection.RemoteIpAddress; + } + static UserAgentService userAgentService = new UserAgentService(); public static string GetClientInfo(this HttpContext httpContext) { - var clientIp = httpContext.Connection.RemoteIpAddress; + var clientIp = httpContext.GetRemoteIPAddress().ToString(); var country = httpContext.Request.Headers["CF-IPCountry"]; var userAgent = httpContext.Request.Headers["User-Agent"]; var builder = new StringBuilder(); builder.AppendLine($"Date: {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}"); - if (clientIp != null) - builder.AppendLine($"IP: {clientIp.ToString()}"); + if (!string.IsNullOrEmpty(country)) + builder.AppendLine($"IP: {clientIp}"); if (!string.IsNullOrEmpty(country)) builder.AppendLine($"Country: {country.ToString()}"); diff --git a/Streetwriters.Identity/Startup.cs b/Streetwriters.Identity/Startup.cs index d6272d5..9554010 100644 --- a/Streetwriters.Identity/Startup.cs +++ b/Streetwriters.Identity/Startup.cs @@ -173,7 +173,7 @@ namespace Streetwriters.Identity { app.UseForwardedHeaders(new ForwardedHeadersOptions { - ForwardedForHeaderName = "CF_CONNECTING_IP", + ForwardedForHeaderName = "CF-Connecting-IP", ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); }