Retrieving correct user IP address in ASP.NET when an HTTP proxy is used

Posted: (EET/GMT+2)

 

In ASP.NET Core, you can use the Request.HttpContext.Connection.RemoteIpAddress inside a controller to get the user's ("requestor") IP address. However, if your application is hosted inside a proxy server (such as YARP, Nginx, etc.), the RemoteIpAddress property only returns the IP address of the proxy server. Thus, the original user's IP address gets hidden.

If you want to get the real user IP address behind a proxy, you can configure your ASP.NET Core web application to read the user's IP address from HTTP headers. Here is an example, place this code snippet before the builder.Build() call:

using Microsoft.AspNetCore.HttpOverrides;

// add support for proxy headers and IP address retrieval
builder.Services.Configure(options =>
{
  options.ForwardedHeaders =
    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  options.KnownProxies.Add(IPAddress.Parse("172.100.1.2"));
});

Here, the IP address configured must match the IP address of the proxy. Here, my solution uses a hardcoded value, but naturally, you could read this from some configuration file/database table, etc. Notice also how multiple proxy IP address could be added; thus, situations like load-balanced proxies are supported.

Once you have code like the above in place, saying:

string requestFromIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString();

...will return the correct IP address of the user, not the proxy's.