Last active
January 10, 2024 10:37
-
-
Save akunzai/7997d8bc520c10f9adf82a777488047d to your computer and use it in GitHub Desktop.
Handle `X-Forwarded-*` headers for OWIN
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
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