Asp.net Core 经过nginx代理后获取不到真实ip和scheme的问题

背景

我最近在一个Asp.net core Web 程序在经过nginx代理后 ,总是获取不到用户真实i和scheme(HttpContext.Request.Scheme),挠头;

我们一般从请求头获取用户ip:(我就用的这种

context.Request.Headers["X-Forwarded-For"]

当然这个时候要去你nginx要配置了 X-Forwarded-For

我们也可以用Forwarded Headers Middleware方式:

Request.HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString();

当然按文档 ,在经过nginx代理后,我们是这样获取用户真实ip和scheme的:

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardedHeaders =
                ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        });
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseForwardedHeaders();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    //...
}

我虽然用的第一种从请求头中获取,但是Forwarded Headers Middleware 以上的这两步配置我都配置了。

后面看到dudu的,配置改为如下:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    //新增如下两行
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
    
    //可以自定义这个头防止伪造X-Forwarded-For攻击,不过我觉得在第一层nginx那里配置 :proxy_set_header X-Forwarded-For $remote_addr; 比较方便,具体不展开了大家自己搜下
    //options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";  
});

安装dudu说法:

如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上 options.KnownNetworks.Clear 与 options.KnownProxies.Clear 的

下面我获取下加了 options.KnownNetworks.Clear(); options.KnownProxies.Clear();与不加,获取的请求头的区别大家有兴趣可以复制下来对比下

获取请求头的代码

访问链接:https://test.mydomain.com/GetRequestHeader

   [HttpGet]
        public IActionResult GetRequestHeader()
        {
            var Scheme = _httpContextAccessor.HttpContext.Request.Scheme;
            var RemoteIpAddress = _httpContextAccessor.HttpContext.Connection?.RemoteIpAddress;
            var RemotePort = _httpContextAccessor.HttpContext.Connection?.RemotePort;
            var Host = _httpContextAccessor.HttpContext.Request?.Host;
            var realip = _httpContextAccessor.HttpContext.RealIp();
            var header = _httpContextAccessor.HttpContext.Request.Headers.ToList();

            return Success("success", new { Scheme, RemoteIpAddress = RemoteIpAddress.ToString(), RemotePort = RemotePort.Value, Host = Host.Value, realip, header });
        }

加Clear()

{
    "status": 1,
    "msg": "success",
    "data": {
        "scheme": "https",
        "remoteIpAddress": "172.16.1.174",
        "remotePort": 0,
        "host": {
            "value": "test.mydomain.com",
            "hasValue": true,
            "host": "test.mydomain.com",
            "port": null
        },
        "realip": "172.16.1.174",
        "header": [
            {
                "Key": "Connection",
                "Value": [
                    "keep-alive"
                ]
            },
            {
                "Key": "Accept",
                "Value": [
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
                ]
            },
            {
                "Key": "Accept-Encoding",
                "Value": [
                    "gzip, deflate, br"
                ]
            },
            {
                "Key": "Accept-Language",
                "Value": [
                    "zh-CN,zh;q=0.9"
                ]
            },
            {
                "Key": "Host",
                "Value": [
                    "test.mydomain.com"
                ]
            },
            {
                "Key": "User-Agent",
                "Value": [
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"
                ]
            },
            {
                "Key": "Upgrade-Insecure-Requests",
                "Value": [
                    "1"
                ]
            },
            {
                "Key": "X-Original-Proto",
                "Value": [
                    "http"
                ]
            },
            {
                "Key": "X-Forwarded-Host",
                "Value": [
                    "test.mydomain.com"
                ]
            },
            {
                "Key": "X-Forwarded-Port",
                "Value": [
                    "443"
                ]
            },
            {
                "Key": "X-Forwarded-Path",
                "Value": [
                    "/rest/api/login/test"
                ]
            },
            {
                "Key": "X-Real-IP",
                "Value": [
                    "172.16.1.174"
                ]
            },
            {
                "Key": "sec-ch-ua",
                "Value": [
                    "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\""
                ]
            },
            {
                "Key": "sec-ch-ua-mobile",
                "Value": [
                    "?0"
                ]
            },
            {
                "Key": "sec-fetch-site",
                "Value": [
                    "none"
                ]
            },
            {
                "Key": "sec-fetch-mode",
                "Value": [
                    "navigate"
                ]
            },
            {
                "Key": "sec-fetch-user",
                "Value": [
                    "?1"
                ]
            },
            {
                "Key": "sec-fetch-dest",
                "Value": [
                    "document"
                ]
            },
            {
                "Key": "X-Original-For",
                "Value": [
                    "[::ffff:172.16.3.119]:53404"
                ]
            }
        ]
    }
}

不加Clear()

{
    "status": 1,
    "msg": "success",
    "data": {
        "scheme": "https",
        "remoteIpAddress": "::ffff:127.0.0.1",
        "remotePort": 52804,
        "host": {
            "value": "test.mydomain.com",
            "hasValue": true,
            "host": "test.mydomain.com",
            "port": null
        },
        "realip": "::ffff:127.0.0.1",
        "header": [
            {
                "Key": "Cache-Control",
                "Value": [
                    "max-age=0"
                ]
            },
            {
                "Key": "Connection",
                "Value": [
                    "close"
                ]
            },
            {
                "Key": "Accept",
                "Value": [
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
                ]
            },
            {
                "Key": "Accept-Encoding",
                "Value": [
                    "gzip, deflate, br"
                ]
            },
            {
                "Key": "Accept-Language",
                "Value": [
                    "zh-CN,zh;q=0.9"
                ]
            },
            {
                "Key": "Cookie",
                "Value": [
                    "_ga=GA1.2.1892895098.1524056233; _39wt_pk_cookie=d87f6237c18985a98db6aa79c0cdabb2-1015182643; _39wt_last_session_cookie=2b9b9210771666befc14a73de4951694-1544111121; _39wt_last_visit_time_cookie=1540012072376; __utma=202198739.1892895098.1524056233.1554648728.1563892800.3; __utrace=d145876b71944eb628f1c8b54da95a0e; money=0; picurl=https%253a%252f%252fpimg.39.net%252fupload%252fmy%252fc200844%252f20190313%252forg%252f7640674.jpg; pid=34820967; username=P52460069; DomainName=P52460069; nickname=%25e5%2593%2588%2A%2A%2A%2A%2A%2A; verify=3105499624; Hm_lvt_9840601cb51320c55bca4fa0f4949efe=1626704188; Hm_lvt_ab2e5965345c61109c5e97c34de8026a=1626704188"
                ]
            },
            {
                "Key": "Host",
                "Value": [
                    "test.mydomain.com"
                ]
            },
            {
                "Key": "User-Agent",
                "Value": [
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
                ]
            },
            {
                "Key": "Upgrade-Insecure-Requests",
                "Value": [
                    "1"
                ]
            },
            {
                "Key": "sec-ch-ua",
                "Value": [
                    "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\""
                ]
            },
            {
                "Key": "sec-ch-ua-mobile",
                "Value": [
                    "?0"
                ]
            },
            {
                "Key": "Sec-Fetch-Site",
                "Value": [
                    "cross-site"
                ]
            },
            {
                "Key": "Sec-Fetch-Mode",
                "Value": [
                    "navigate"
                ]
            },
            {
                "Key": "Sec-Fetch-User",
                "Value": [
                    "?1"
                ]
            },
            {
                "Key": "Sec-Fetch-Dest",
                "Value": [
                    "document"
                ]
            },
            {
                "Key": "X-Original-For",
                "Value": [
                    "[::ffff:127.0.0.1]:52804"
                ]
            },
            {
                "Key": "X-Original-Proto",
                "Value": [
                    "http"
                ]
            }
        ]
    }
}

PS:注意本文请求都是经过nginx的情况下,且只有一层nginx;

引用

https://www.cnblogs.com/dudu/p/11088645.html

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-3.1

posted @ 2021-07-27 18:53  乔达摩  阅读(52)  评论(0编辑  收藏  举报