Asp.NET Core Nginx Ocelot ForwardedHeaders X-Forwarded-For

原文:Asp.NET Core Nginx Ocelot ForwardedHeaders X-Forwarded-For

ocelot在部署时我使用了nginx作为转发,并配置了https证书,但是发现ocelot不支持Forward host header。
https://ocelot.readthedocs.io/en/latest/introduction/notsupported.html
这时候我就有了个疑问,Forward host header到底时什么含义?于是便有了本文。

nginx等代理服务器在转发时,会使用X-Forwarded-For 请求头。该请求头会记录从请求者ip到层层代理服务器ip的信息。

https://imququ.com/post/x-forwarded-for-header-in-http.html
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

asp.net core 在使用转发服务器后,官方文档说需要使用中间件设置XForwardedFor与XForwardedProto
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2#when-to-use-kestrel-with-a-reverse-proxy

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

app.UseAuthentication();

使用X-Forwarded-For会更新 HttpContext.Connection.RemoteIpAddress
使用X-Forwarded-Proto会更新 HttpContext.Request.Scheme
使用X-Forwarded-Host会更新 HttpContext.Request.Host
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2

我建立了一些测试的webapi来查看效果

Copy        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var remoteIp = HttpContext.Connection.RemoteIpAddress;
            string ip = remoteIp.MapToIPv4().ToString();
            var scheme = HttpContext.Request.Scheme;
            string sch = scheme.ToString();
            var host = HttpContext.Request.Host;
            string ho = host.ToString();
            return new string[] { ip,sch,ho };
        }

是否使用中间件,会影响到http和RemoteIPAddress的值是否正确。

而使用了ocelot转发api后,无法读取到host的正确值。ocelot无需添加中间件 ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
如果添加了,反而会无法获取到正确的remoteip以及scheme

相关推荐