Skip to content

Instantly share code, notes, and snippets.

@heemskerkerik
Last active March 13, 2019 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heemskerkerik/2e3a5b1b5088e28c7cc370f466cbef1d to your computer and use it in GitHub Desktop.
Save heemskerkerik/2e3a5b1b5088e28c7cc370f466cbef1d to your computer and use it in GitHub Desktop.
Test program to reproduce an issue with the way X-Forwarded-For is handled by ForwardedHeadersMiddleware
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" />
</ItemGroup>
</Project>
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
namespace ForwardedHeadersTest
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All });
app.Run(
async context =>
{
var header = context.Request.Headers["X-Forwarded-For"];
string joinedHeader = header.Any() ? string.Join("\r\n", header) : "";
await context.Response.WriteAsync(
$"X-Forwarded-For:\r\n{joinedHeader}\r\nRemote IP: {context.Connection.RemoteIpAddress}"
);
}
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment