Skip to content

Instantly share code, notes, and snippets.

@Philo
Last active June 20, 2019 20:26
Show Gist options
  • Save Philo/9b1bfecbbafa0ffdc98fbcdd367776d1 to your computer and use it in GitHub Desktop.
Save Philo/9b1bfecbbafa0ffdc98fbcdd367776d1 to your computer and use it in GitHub Desktop.
Configure proxy headers .net core.
namespace Philo.Start.Forwarding
{
using System;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
public class ConfigureForwardedHeadersOptions : IConfigureNamedOptions<ForwardedHeadersOptions>
{
private const string ProxyNetworksConfigName = "ProxyNetworks";
private static Regex pattern = new Regex(@"^(?<prefix>(?:[0-9]{1,3}\.){3}[0-9]{1,3})\/(?<prefixLength>(?:[0-9]|[1-2][0-9]|3[0-2]))?$", RegexOptions.Compiled | RegexOptions.Singleline);
private readonly IConfiguration configuration;
public ConfigureForwardedHeadersOptions(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Configure(ForwardedHeadersOptions options)
{
Configure(Options.DefaultName, options);
}
public void Configure(string name, ForwardedHeadersOptions options)
{
configuration.GetSection(nameof(ForwardedHeadersOptions)).Bind(options);
var proxyNetworks = configuration.GetValue<string>(ProxyNetworksConfigName) ?? string.Empty;
if (!string.IsNullOrWhiteSpace(proxyNetworks))
{
foreach (var cidr in proxyNetworks.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim()))
{
var match = pattern.Match(cidr);
if (match.Success && match.Groups["prefix"].Success && match.Groups["prefixLength"].Success &&
int.TryParse(match.Groups["prefixLength"].Value, out var prefixLength))
{
var prefix = match.Groups["prefix"].Value;
options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse(prefix), prefixLength));
}
}
if ((options.KnownNetworks?.Any() ?? false) || (options.KnownProxies?.Any() ?? false))
{
options.ForwardLimit = null;
}
}
}
}
}
namespace Philo.Start.Forwarding
{
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
public static class ForwardedHeadersOptionsServiceCollectionExtensions
{
public static IServiceCollection ConfigureForwardedHeaders(this IServiceCollection services)
{
return
services.AddTransient<IConfigureOptions<ForwardedHeadersOptions>, ConfigureForwardedHeadersOptions>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment