Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active January 10, 2024 10:37
Show Gist options
  • Save akunzai/7997d8bc520c10f9adf82a777488047d to your computer and use it in GitHub Desktop.
Save akunzai/7997d8bc520c10f9adf82a777488047d to your computer and use it in GitHub Desktop.
Handle `X-Forwarded-*` headers for OWIN
public class ForwardedHeadersMiddleware : OwinMiddleware
{
public ForwardedHeadersMiddleware(OwinMiddleware next) : base(next)
{
}
public override Task Invoke(IOwinContext context)
{
if (string.Equals(context.Request.Headers["X-Forwarded-Proto"], "https",
StringComparison.OrdinalIgnoreCase))
{
context.Request.Scheme = "https";
}
var forwardedForHeader = context.Request.Headers["X-Forwarded-For"];
if (!string.IsNullOrWhiteSpace(forwardedForHeader))
{
context.Request.RemoteIpAddress = forwardedForHeader;
}
var forwardedHost = context.Request.Headers["X-Forwarded-Host"];
if (!string.IsNullOrWhiteSpace(forwardedHost))
{
context.Request.Host = new HostString(forwardedHost);
}
var forwardedPrefix = context.Request.Headers["X-Forwarded-Prefix"];
if (!string.IsNullOrWhiteSpace(forwardedPrefix))
{
context.Request.PathBase = new PathString(forwardedPrefix);
}
return Next.Invoke(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment