Last active
November 15, 2017 19:13
-
-
Save eldavido/b52deb7b5b8c25cbbf0cb473eacdbee6 to your computer and use it in GitHub Desktop.
Ensure a reverse-proxied ASP.NET Core application uses https
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 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