Configuring ASP.NET Core Behind a Load Balancer

ASP.NET Core behind a Load BalancerIf you deploy your ASP.NET Core web application to the cloud you are likely putting it behind a load balancer.  Here’s some quick info that might provide useful for how to Configure ASP.NET Core behind a load balancer.

Forwarded Headers

There are generally 3 headers which are added to the request header to tell your application about how it was forwarded from the load balancer.

  • X-Forwarded-For: List of comma space list of IP addresses of the original client and proxies that received the request.
  • X-Forwarded-Proto: The scheme from the original client and proxies.
  • X-Forwarded-Host: Original host header.

SSL Termination

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.

Note: I strongly believe you should use SSL all the way through to your application.  HTTPS everywhere.

However, if you are using SSL termination, you can run into an issue of any links generated by the application will not be to HTTPS, but rather HTTP since that is how your application is running.

For example, if you are using Authentication middleware and the Authorize attribute, when a user is not logged in, and they are redirected to the LoginPath, they will be redirect to HTTP instead of the originating HTTPS, which they requested to begin with.

ASP.NET Core Behind a Load Balancer

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

Note: By default, which seems confusing, is the UseForwardedHeaders without any parameters is to ForwardedHeaders.None.

HTTPS Everywhere

ASP.NET Core 2.1 has announced improvements for using HTTPS during development which should hopefully help push adoption for HTTP everywhere.

ASP.NET Core 2.1 makes it easy to both develop your app with HTTPS enabled and to configure HTTPS once your app is deployed. The ASP.NET Core 2.1 project templates have been updated to enable HTTPS by default. To enable HTTPS in production simply configure the correct server certificate.

If you are using SSL termination, I’d love to hear why and in what situations?  Please let me know in the comments or on Twitter.

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.