0

I have an ASP.NET Core 6 project deployed as AWS Lambda NET6 runtime and before the upgrade from 3.1 to 6 the code below worked fine returning the remote IP address even when invoked locally.

IHttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString()

Now when I run it locally it resolves to ::1 and I have read that this might be a problem due to localhost which is something I need to overcome since I rely upon the remote IP address.

From articles found in SO (This, This, and This) I have tried the below.

Adding the below middleware in Startup.cs

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                       ForwardedHeaders.XForwardedProto
});

Also added an endpoint to check what is returned locally and the deployed AWS Lambda (works fine).

[HttpGet("ipaddress")]
public IActionResult GetRemoteIpAddress(CancellationToken cancellationToken)
{
   return new JsonResult(new
   {
       requestContextConnection = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
       httpContextaccessorContextConnection = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(),
       getRequestIp = GetRequestIP()
   });
}

Method GetRequestIP() retrieved from this answer. From the below endpoint I get the below results. Localhost:

{
    "requestContextConnection": "::1",
    "httpContextaccessorContextConnection": "::1",
    "getRequestIp": "::1"
}

AWS Lambda deployed:

{
    "requestContextConnection": "SOME.IP.207",
    "httpContextaccessorContextConnection": "SOME.IP.207",
    "getRequestIp": "SOME.IP.207"
}

How can I fix the localhost issue that is not supported in Kestrel; (from my understanding); I use SDK 6.0.201.

George Taskos
  • 8,324
  • 18
  • 82
  • 147

0 Answers0