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

2021-02-15 14:23

阅读:652

标签:html   cer   app   pre   view   ret   sop   button   ref   

原文: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

Copy
app.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 ActionResultstring
>> 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

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

标签:html   cer   app   pre   view   ret   sop   button   ref   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12983755.html


评论


亲,登录后才可以留言!