Refactor ForwardedHeaders configuration to improve proxy and network handling
Updated the ForwardedHeadersOptions configuration in Program.cs to utilize a new ReadList method for better handling of known proxies and networks. This change allows for flexible input from environment variables and appsettings, ensuring proper parsing of both comma-separated values and array formats. Enhanced code readability and maintainability by consolidating the logic for reading configuration values.
This commit is contained in:
@@ -38,26 +38,35 @@ builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
|
||||
foreach (
|
||||
var proxy in builder
|
||||
.Configuration.GetSection("ForwardedHeaders:KnownProxies")
|
||||
.Get<string[]>()
|
||||
?? []
|
||||
)
|
||||
foreach (var proxy in ReadList(builder.Configuration, "ForwardedHeaders:KnownProxies"))
|
||||
options.KnownProxies.Add(IPAddress.Parse(proxy));
|
||||
|
||||
foreach (
|
||||
var network in builder
|
||||
.Configuration.GetSection("ForwardedHeaders:KnownNetworks")
|
||||
.Get<string[]>()
|
||||
?? []
|
||||
)
|
||||
foreach (var network in ReadList(builder.Configuration, "ForwardedHeaders:KnownNetworks"))
|
||||
{
|
||||
var parts = network.Split('/');
|
||||
options.KnownIPNetworks.Add(
|
||||
new System.Net.IPNetwork(IPAddress.Parse(parts[0]), int.Parse(parts[1]))
|
||||
);
|
||||
}
|
||||
|
||||
// Список доверенных прокси/сетей приходит из .env одной строкой (env-переменная по одному ключу
|
||||
// в string[] не биндится) — принимаем и запятые, и массив appsettings/индексы __0. Иначе
|
||||
// задокументированная в .env.example запись через запятую молча игнорировалась бы, оставляя
|
||||
// доверие только loopback и обрывая подхват X-Forwarded-Proto.
|
||||
static string[] ReadList(IConfiguration config, string key)
|
||||
{
|
||||
var array = config.GetSection(key).Get<string[]>();
|
||||
if (array is { Length: > 0 })
|
||||
return array;
|
||||
|
||||
var scalar = config[key];
|
||||
return string.IsNullOrWhiteSpace(scalar)
|
||||
? []
|
||||
: scalar.Split(
|
||||
',',
|
||||
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
Reference in New Issue
Block a user