If you are using a reverse proxy, you should read this guide from Microsoft.
Essentially, your reverse proxy should provide these headers to your ASP.NET Core Application:
X-Forwarded-For
- The client IP
X-Forwarded-Host
- The Host
header from the client (e.g. www.example.com:80
)
X-Forwarded-Proto
- The protocl (e.g. HTTPS
)
Then you need to configure your ASP.NET Core application to accept them. You can do so by calling the app.UseForwardedHeaders() method in your Startup's Configure
method.
By default (if I'm reading the docs correctly) UseForwardedHeaders
(called as above) will accept X-Forwarded-For
and X-Forwarded-Proto
from a localhost
reverse proxy.
If your situation is more complicated than that, you must configure the headers you want/the trusted reverse proxies:
var forwardedOptions = new ForwardedHeadersOptions()
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedHost | ForwardedHeaders.XForwardedProto // allow for, host, and proto (ForwardedHeaders.All also works here)
};
// if it's a single IP or a set of IPs but not a whole subnet
forwardedOptions.KnownProxies.Add(IPAddress.Parse("192.168.0.5"));
// if it's a whole subnet
forwardedOptions.KnownNetworks.Add(new IPNetwork("192.168.0.1", 24)); // 192.168.0.1 - 192.168.0.254
app.UseForwardedHeaders(forwardedOptions);
Also note that, depending on the reverse proxy you use, you might need to configure this on the reverse proxy