I am working to get my .net core 1.1 application working behind a load balancer and enforcing https. I have the following setup in my Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IOptions<Auth0Settings> auth0Settings)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var startupLogger = loggerFactory.CreateLogger<Startup>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
startupLogger.LogInformation("In Development");
}
else
{
startupLogger.LogInformation("NOT in development");
app.UseExceptionHandler("/Home/Error");
}
app.UseMiddleware<HttpsRedirectMiddleware>();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});`
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme= CookieAuthenticationDefaults.AuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieHttpOnly = true,
SlidingExpiration = true
});
The HttpsRedirectMiddleware is for validating the LB has the X-Forwarded-Proto set, it does, and comes back as https as the only value. When I go to the site (https://myapp.somedomain.net), it knows I am not authenticated and redirects me to (http://myapp.somedomain.net/Account/Logon?ReturnUrl=%2f). It loses the SSL connection and switched back over to port 80 on me. The .net core documentation says to use "UseForwardedHeaders" like below, which does not work in my case. The console logger does not have any error or warnings from the middleware when this switch happens.
For a short term fix, I have put this below "UseForwardedHeaders"
app.Use(async (context, next) =>
{
var xproto = context.Request.Headers["X-Forwarded-Proto"].ToString();
if (xproto!=null && xproto.StartsWith("https", StringComparison.OrdinalIgnoreCase)){
startupLogger.LogInformation("Switched to https");
context.Request.Scheme = "https";
}
await next();
});
The above works perfect, but is a hack. I would like to do it the correct way.
.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, you can clear the Known Networks and Known Proxies to accept any forwarded requests. Still best to have a firewall setup or lock the known networks down to a private subnet.
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.
What this does is updates the Request.Scheme with the X-Forwarded-Proto header so that all redirects link generation uses the correct scheme.