简体   繁体   English

反向代理后面的 ASP.Net Core 不使用 `X-Forwareded-For`

[英]`X-Forwareded-For` is not used by ASP.Net Core behind reverse proxy

I am trying to get the remote IP address of a request (ie, the IP of the client who sent the request) in my ASP.Net Core 2.1 MVC Controller (runs in .Net Docker container).我试图在我的ASP.Net Core 2.1 MVC 控制器(在 .Net Docker 容器中运行)中获取请求的远程 IP 地址(即发送请求的客户端的 IP)。 Taking into consideration that My ASP.Net Core application is located behind NGINX reverse proxy (runs in NGINX Docker container).考虑到我的 ASP.Net Core 应用程序位于 NGINX 反向代理之后(在 NGINX Docker 容器中运行)。

As known, when the reverse proxy redirects the request to my .Net Core application, it will change the source IP of my request (TCP/IP layer), therefore, I configured NGINX to add X-Forwareded-For with the original IP to the request.众所周知,当反向代理将请求重定向到我的 .Net Core 应用程序时,它会更改我请求的源 IP(TCP/IP 层),因此,我将 NGINX 配置为将带有原始 IP 的X-Forwareded-For添加到请求。 The request that is redirected from NGINX container to .Net container has X-Forwareded-For in the header:从 NGINX 容器重定向到 .Net 容器的请求在标头中有X-Forwareded-For

在此处输入图片说明

And of course, I configured .Net Core to know about that:当然,我配置了 .Net Core 以了解这一点:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    // Rewrite the header when being redirected (this is required because we are behind reverse proxy)
    var forwardedHeadersOptions = new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
        KnownProxies = { IPAddress.Parse("172.20.10.2"), IPAddress.Parse("172.20.10.3"), IPAddress.Parse("172.20.10.4") },
    };

    forwardedHeadersOptions.KnownNetworks.Add(
        new IPNetwork(IPAddress.Parse("172.0.0.0"), 8));
    forwardedHeadersOptions.KnownNetworks.Add(
        new IPNetwork(IPAddress.Parse("127.0.0.1"), 8));

    app.UseForwardedHeaders(forwardedHeadersOptions);
    ...

However, HTTPContext.Connection.RemoteIPAddress still returning 172.20.10.3 (NGINX container IP, not the real remote IP):但是, HTTPContext.Connection.RemoteIPAddress仍然返回 172.20.10.3(NGINX 容器 IP,不是真正的远程 IP):

logger.LogDebug("Remote IP Address: " + Request.HttpContext.Connection.RemoteIpAddress.ToString());

Remote IP Address: 172.20.10.3远程 IP 地址:172.20.10.3

I checked my header in .Net Core, it has X-Forwareded-For with the correct original remote IP address:我在 .Net Core 中检查了我的标题,它有X-Forwareded-For和正确的原始远程 IP 地址:

logger.LogDebug("X-Forwareded-For Header Feature: " + HttpContext.Request.Headers["X-Forwarded-For"]);

X-Forwareded-For Header Feature: 85.XX.4.121 X-Forwarded-For 标题功能:85.XX.4.121

Does someone have any idea what I am missing?有人知道我缺少什么吗? Why RemoteIPAddress still returning the IP of the NGINX docker container instead of the real remote IP address?为什么 RemoteIPAddress 仍然返回 NGINX docker 容器的 IP 而不是真正的远程 IP 地址?

Update更新

My Program.cs我的程序Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5000")
            .UseStartup<Startup>()
            .Build();
}

I tried Also to configure the the ForwarededHeadersOptions by configuring its service like this:我还尝试通过如下配置其服务来配置ForwarededHeadersOptions

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    //options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("172.0.0.0"), 8));
    options.RequireHeaderSymmetry = false;
    options.ForwardLimit = null;
    options.KnownProxies.Add(IPAddress.Parse("172.20.10.3"));
    //options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("127.0.0.1"), 8));
});

With no success...没有成功...

UPDATE 2更新 2

OK I guess I am on the right way, the IP address returned by RemoteIPAddress was ::ffff:172.20.10.20, not 172.20.10.20!好的,我想我走对了, RemoteIPAddress返回的 IP 地址是 ::ffff:172.20.10.20,而不是 172.20.10.20! I did not know that they are different.我不知道他们是不同的。 The official documentation helped me to discover that. 官方文档帮助我发现了这一点。

The IP I got from RemoteIPAddress was IPv4 represented as IPv6 (was ::ffff:172.20.10.20, not 172.20.10.20!).我从RemoteIPAddress获得的 IP 是表示为 IPv6 的 IPv4(是 ::ffff:172.20.10.20,而不是 172.20.10.20!)。 I was using only IPv4 part of the IP, therefore the KnownProxies in my case were wrong.我只使用了 IP 的 IPv4 部分,因此在我的情况下, KnownProxies是错误的。 I should have entered the full IPv4 address also with the v6 representation part.我也应该在 v6 表示部分输入完整的 IPv4 地址。

The official documentation showed that:官方文档显示:

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.1 https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.1

UPDATE as requested by a comment:根据评论的要求更新:

So in my case, the code should look like this:所以在我的例子中,代码应该是这样的:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.RequireHeaderSymmetry = false;
    options.ForwardLimit = null;
    options.KnownProxies.Add(IPAddress.Parse("::ffff:172.20.10.20")); // <<-- Notice the full format of the IP address.
});

As per the official documentation, if you are using Apache or Nginx integration , following code should be added to the Startup.ConfigureServices method.根据官方文档,如果您使用Apache 或 Nginx 集成,则应将以下代码添加到Startup.ConfigureServices方法中。

// using Microsoft.AspNetCore.HttpOverrides;

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | 
            ForwardedHeaders.XForwardedProto;
        // Only loopback proxies are allowed by default.
        // Clear that restriction because forwarders are enabled by explicit 
        // configuration.
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();
    });

and then on top of everything, in Configure method use然后最重要的是,在Configure方法中使用

app.UseForwardedHeaders();

Further suppose in nginx conf file, inside a location, use进一步假设在 nginx conf 文件中,在一个位置内,使用

proxy_set_header   Host $host;
proxy_set_header   X-Real-IP $remote_addr;
proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header   X-Forwarded-Host $server_name;

Now the first entry in the X-Forwarded-For will be the real client IP.现在X-Forwarded-For的第一个条目将是真实的客户端 IP。

IMPORTANT: If you want to secure the app and not allow an attacker inject X-Forwarded-For, Please following this Nginx Dealing with invalid headers重要提示:如果您想保护应用程序并且不允许攻击者注入 X-Forwarded-For,请按照此Nginx 处理无效标头

Please see Forward the scheme for Linux and non-IIS reverse proxies and Configure Nginx请参阅转发 Linux 和非 IIS 反向代理的方案配置 Nginx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NGINX反向代理背后的ASP.NET MVC - ASP.NET MVC behind NGINX reverse proxy 具有Apache和反向代理的Linux ASP.Net核心 - Linux ASP.Net core with Apache and reverse proxy ASP.NET Core YARP 反向代理多个监听端口 - ASP.NET Core YARP Reverse Proxy multiple listen ports How to set BaseUrl for Swagger in ASP.NET Core Web API using NSwag.AspNetCore (when hosted behind a reverse proxy) - How to set BaseUrl for Swagger in ASP.NET Core Web API using NSwag.AspNetCore (when hosted behind a reverse proxy) ASP.NET Core 2.x-代理服务提供商 - ASP.NET Core 2.x - Proxy Service Provider ASP.NET Core Razor 在使用 Apache 作为反向代理时无法设置 cookie - ASP.NET Core Razor unable to set cookies when using Apache as reverse proxy ASP.NET Core 404 响应中的 Servce Fabric 反向代理集成 - Servce Fabric Reverse Proxy Integration in ASP.NET Core 404 Response 如何使用集群内反向代理自动确定在Kubernetes中运行的ASP.NET Core应用程序的KnownNetworks? - How to automatically determine KnownNetworks for ASP.NET Core application running in Kubernetes with an in-cluster reverse proxy? 如何知道在 ASP.net 内核中使用了哪些函数以及我可以使用哪些函数(逆向工程) - How to know which functions are used and which can I use (reverse engineering) in ASP.net core Stackify在ASP.NET Core中未使用代理 - Stackify not using proxy in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM