4

I have an ASP.NET Core webapi running in an on-prem bare-metal Kubernetes cluster. There's no external load-balancer, and I'm using NGINX ingress.

I want to get the users' IP address, and am using HttpContext.Connection.RemoteIpAddress in the .NET code.

Unfortunately, this is picking up the IP address of the nginx ingress (possibly the controller given the namespace)...

::ffff:10.244.1.85

Doing a reverse DNS lookup resolves that to...

10-244-1-85.ingress-nginx.ingress-nginx.svc.cluster.local

After a little bit of Googling, I tried adding externalTrafficPolicy: "Local" to my service definition, but that didn't make a difference.

This seems like something that should be really trivial and quite a common requirement. Any ideas?

Dan
  • 5,692
  • 3
  • 35
  • 66
  • 1
    Does this question provide a useful answer? https://stackoverflow.com/questions/39774846/preserving-remote-client-ip-with-ingress – Paul Annetts Feb 12 '19 at 15:17
  • Unfortunately that's not making a difference. – Dan Feb 13 '19 at 17:36
  • Can you post the configuration of ingress? – Crou Feb 14 '19 at 09:26
  • 1
    Have you checked the HTTP headers in your web application? The typical solution would be to set X-Forwarded-For in Nginx and use it in the application. If the header is missing use the remote address, if it is present use the value from the header. – ewramner Feb 21 '19 at 14:53
  • @ewramner I hadn't checked the headers. Just tried it, and the header is there, but it's set to "10.244.1.0" which is internal to the cluster, not my machine's IP address. – Dan Feb 21 '19 at 16:47

1 Answers1

3

First try to get ip from header X-Forwarded-For as shown below, if it's null then you can use Connection.RemoteIpAddress. Also make sure your nginx configmap has proxy enabled as per screenshot:
enter image description here

var ip = IPAddress.Parse(_accessor.ActionContext.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault());
            if (string.IsNullOrEmpty(ip.ToString()))
            {
                ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4();
            }
kadamb
  • 1,532
  • 3
  • 29
  • 55
Nisarg Parikh
  • 31
  • 1
  • 5