Skip to content

Instantly share code, notes, and snippets.

@cilliemalan
Created July 14, 2016 08:49
Show Gist options
  • Save cilliemalan/4fa62f88bbd0775a95a59a79cd00e117 to your computer and use it in GitHub Desktop.
Save cilliemalan/4fa62f88bbd0775a95a59a79cd00e117 to your computer and use it in GitHub Desktop.
A better load balancer HTTPS redirect
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Whatevs
{
public partial class Startup
{
private IAppBuilder UseSecurityChecks(IAppBuilder app)
{
app.Use((context, next) =>
{
string[] proto;
if (context.Request.Headers.TryGetValue("X-Forwarded-Proto", out proto) && proto.FirstOrDefault() == "http")
{
context.Response.StatusCode = 301;
context.Response.Headers["Location"] = Regex.Replace(context.Request.Uri.ToString(), "^https|^http", "https");
return Task.CompletedTask;
}
else
{
return next();
}
});
return app;
}
}
}
@cilliemalan
Copy link
Author

You may be wondering "why are we replacing http or https for the location?" The reason is that the load balancer itself might be connecting to the web server via https (not uncommon and is set up this way in our environment). In this case the web server might put https for the scheme even though the client connected insecurely to the load balancer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment