Created
August 4, 2022 22:07
-
-
Save jglozano/2c72f95611c4f6630214e7ac61b065c2 to your computer and use it in GitHub Desktop.
OWIN Middleware for X-FORWARDED- Headers
This file contains hidden or 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 Microsoft.Owin; | |
using Owin; | |
using System.Threading.Tasks; | |
[assembly: OwinStartup(typeof(OWINSample.Startup))] | |
namespace OWINSample | |
{ | |
public class Startup | |
{ | |
public void Configuration(IAppBuilder app) | |
{ | |
// Ensure this is the top most middleware | |
app.Use<XForwardedMiddleware>(); | |
} | |
} | |
public class XForwardedMiddleware : OwinMiddleware | |
{ | |
public XForwardedMiddleware(OwinMiddleware next) : base(next) | |
{ | |
} | |
public override Task Invoke(IOwinContext context) | |
{ | |
var request = context.Request; | |
var forwardedFor = request.Headers["X-Forwarded-For"]; | |
var forwardedProto = request.Headers["X-Forwarded-Proto"]; | |
var forwardedHost = request.Headers["X-Forwarded-Host"]; | |
if (!string.IsNullOrWhiteSpace(forwardedFor)) | |
{ | |
request.RemoteIpAddress = forwardedFor; | |
} | |
if (!string.IsNullOrWhiteSpace(forwardedProto)) | |
{ | |
request.Scheme = forwardedProto; | |
} | |
if (!string.IsNullOrWhiteSpace(forwardedHost)) | |
{ | |
request.Host = new HostString(forwardedHost); | |
} | |
return Next.Invoke(context); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment