nginxazure-cdnazure-front-door

Get client IP address using Nginx and Azure Front Door


I am using an Azure WebApp (docker-compose) which has Nginx as reverse proxy and .net core app. Last year our number of clients increased a lot and we started using Azure Front Door as CDN for caching static content. Problem is now we no longer are able to get client IP address for our logging SQL table.

This is the code that works without the AFD:

Nginx default.conf:

    proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header          X-Forwarded-Proto $scheme;

Dotnet Startup.cs:

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

But adding the AFD it always gets the IP address of the CDN.

I know AFD passes X-Azure-ClientIP header, but I was not able to get it in Nginx or dotnet.

Do you know how can I get real client IP address using Azure Front Door, Nginx and dotnet core?

Thanks in advance.


Solution

  • It worked this way:

    1. Nginx:
    server {
      listen                      8080;
      server_name                 *.pragmaticworkstraining.com *.staging.pragmaticworkstraining.com localhost;
      client_max_body_size        1024M;
      client_header_timeout       36000;
      client_body_timeout         36000; 
      proxy_connect_timeout       75s; 
      proxy_read_timeout          36000; 
      proxy_send_timeout          36000;
    
      location / {
        proxy_pass                http://web-site:5000;
        proxy_http_version        1.1;
        proxy_set_header          Upgrade $http_upgrade;
        proxy_set_header          Connection $http_connection;
        proxy_set_header          Host $host;
        proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header          X-Forwarded-Proto $scheme;
        proxy_cache_bypass        $http_upgrade;
        gzip                      on;
        gzip_types                text/plain text/css application/xml application/javascript font/woff2 image/x-icon;
      }
    }
    

    dotnet:

    string ip = _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].ToString();
    string[] ipRange = ip.Split(',');
    clientIp = ipRange[0];