I have a .Net 5 app with a SignalR hub and i want to get the client's IP from the "X-forwarded-for". My app is behind a load balancer so getting the RemoteIpAddress always returns a 10.x.x.x Ip.
Starting with HubCallerContext i can get a IHttpConnectionFeature from its features
var httpReq = Context.Features.Get<IHttpConnectionFeature>();
And when debugging i can see that the object contains a RequestHeader, but i can only access LocalIpAddress, RemoteIpAddress, LocalPort, and ConnectionId.
Calling httpReq.RequestHeaders does not let me compile the app.
Is there any way of getting the headers from either the IHttpConnectionFeature or DefaultHubCallerContext?
CodePudding user response:
You can use the middleware IApplicationBuilder#UseForwardedHeaders from Microsoft.AspNetCore.Builder.ForwardedHeadersExtensions.
This middleware updates RemoteIpAddress to the client's IP, as long all proxies update correctly the header X-Forwarded-For and that the options are correct (We have to either hardcode the number of proxies or tell the IP/network that we can trust).
In your Startup.cs add the following middleware to the Configure method:
app.UseForwardedHeaders();
Then in ConfigureServices you have to configure it:
services.Configure<ForwardedHeadersOptions>(options =>
{
...
});
More information about the options and this in: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0#forwarded-headers-middleware-options
