Created
July 14, 2016 08:49
-
-
Save cilliemalan/4fa62f88bbd0775a95a59a79cd00e117 to your computer and use it in GitHub Desktop.
A better load balancer HTTPS redirect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You may be wondering "why are we replacing
http
orhttps
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.