get real client ip address in dotnet core when usi

2020-07-14 06:02发布

问题:

I'm using dotnet core. I'm grabbing the IP address using the line Request.HttpContext.Connection.RemoteIpAddress.ToString(). When I visit my site using my ip address I see the client ip address showing correctly. However I want to use https and I use nginx. So in my location I wrote

    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-For $remote_addr;
    proxy_set_header  X-Forwarded-Host $remote_addr;

When I visit my site through the domain my ipaddress shows as ::1 and 127.0.0.1 (they switch every time I refresh). My nginx config is below I'm not exactly sure how to tell .net core the real ip address


server {
    server_name         www.example.com;
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    root                /var/www/example.com/;
    add_header          Strict-Transport-Security "max-age=31536000";
    index index.html index.htm;
    log_not_found off;
    access_log off;
    #try_files $uri.html $uri $uri/ =404;
    expires max;
    default_type text/plain;
    include /etc/nginx/mime.types;

    index off;
    location ~/other/ {
        index off;
        autoindex on;
    }

    location /abc {
        proxy_pass http://localhost:5050;
        proxy_http_version 1.1;
        proxy_set_header  X-Real-IP $remote_addr;
        proxy_set_header  X-Forwarded-Proto https;
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  X-Forwarded-Host $remote_addr;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

回答1:

Forwarded headers are not processed by default. You need to use HttpOverrides middleware.

  • add Microsoft.AspNetCore.HttpOverrides as dependency
  • add the following to your Configure method:

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


回答2:

I am using .Net Core 2.2, and found the following to work. It's slightly different than the other answer (which I couldn't get to work).

  • Add Microsoft.AspNetCore.HttpOverrides as dependency
  • Add the following to the ConfigureServices method:

 

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
  • Add the following to the Configure method:

 

app.UseForwardedHeaders();

Source: Configure ASP.NET Core to work with proxy servers and load balancers