Skip to content

Instantly share code, notes, and snippets.

@eldavido
Last active November 15, 2017 19:13
Show Gist options
  • Save eldavido/b52deb7b5b8c25cbbf0cb473eacdbee6 to your computer and use it in GitHub Desktop.
Save eldavido/b52deb7b5b8c25cbbf0cb473eacdbee6 to your computer and use it in GitHub Desktop.
Ensure a reverse-proxied ASP.NET Core application uses https
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace interval.Support {
public class ReverseProxyHttpsEnforcer {
private const string ForwardedProtoHeader = "X-Forwarded-Proto";
private readonly RequestDelegate _next;
public ReverseProxyHttpsEnforcer(RequestDelegate next) {
_next = next;
}
public async Task Invoke(HttpContext ctx) {
var h = ctx.Request.Headers;
if (h[ForwardedProtoHeader] == string.Empty || h[ForwardedProtoHeader] == "https") {
await _next(ctx);
} else if (h[ForwardedProtoHeader] != "https") {
var withHttps = $"https://{ctx.Request.Host}{ctx.Request.Path}{ctx.Request.QueryString}";
ctx.Response.Redirect(withHttps);
}
}
}
public static class ReverseProxyHttpsEnforcerExtensions {
public static IApplicationBuilder UseReverseProxyHttpsEnforcer(this IApplicationBuilder builder) {
return builder.UseMiddleware<ReverseProxyHttpsEnforcer>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment