.net Core X Forwarded Proto not working

If you are using a load balancer, it is common to have the load balance terminate the SSL connection and send the request to your application over HTTP.

This worked for me. I am using SSL termination on AWS Load Balancer.

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedProto
});

What this does is updates the Request.Scheme with the X-Forwarded-Proto header so that all redirects link generation uses the correct scheme.

X-Forwarded-Proto: The scheme from the original client and proxies.


.NET Core has a default set for the forwarded headers. It defaults to 127.0.0.1, for IIS integration.

After tracking down the source code, I found that you can clear the KnownNetworks and KnownProxies lists to accept any forwarded requests. However, it is still best to have a firewall setup or lock the known networks down to a private subnet.

var forwardingOptions = new ForwardedHeadersOptions()
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
forwardingOptions.KnownNetworks.Clear(); // Loopback by default, this should be temporary
forwardingOptions.KnownProxies.Clear(); // Update to include

app.UseForwardedHeaders(forwardingOptions);

Update for .NET Core 2.x: Remember setting the IP of your proxy/load balancer or the private network after debugging the issue. This prevents bypassing your proxy/load balancer and faking the Forwarded-For headers.

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;

    // Replace with IP of your proxy/load balancer
    options.KnownProxies.Add(IPAddress.Parse("192.168.1.5"));

    // 192.168.1.0/24 allows any from 192.168.1.1-254;
    options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("192.168.1.0"), 24));
});

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#forwarded-headers-middleware-options