40 lines
1.1 KiB
C#
40 lines
1.1 KiB
C#
using System.Net;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Http.Middleware;
|
|
|
|
internal sealed class RealIpMiddleware(RequestDelegate next, IOptions<ForwardedHeadersOptions> options)
|
|
{
|
|
private const string RealIpHeader = "X-Real-IP";
|
|
private const string OriginalForHeader = "X-Original-For";
|
|
|
|
public Task InvokeAsync(HttpContext context)
|
|
{
|
|
var headers = context.Request.Headers;
|
|
var remoteIp = context.Connection.RemoteIpAddress;
|
|
|
|
if (!headers.ContainsKey(OriginalForHeader)
|
|
&& remoteIp is not null
|
|
&& IsTrustedProxy(remoteIp)
|
|
&& IPAddress.TryParse(headers[RealIpHeader].ToString(), out var realIp))
|
|
{
|
|
context.Connection.RemoteIpAddress = realIp;
|
|
}
|
|
|
|
return next(context);
|
|
}
|
|
|
|
private bool IsTrustedProxy(IPAddress ip)
|
|
{
|
|
if (ip.IsIPv4MappedToIPv6)
|
|
{
|
|
ip = ip.MapToIPv4();
|
|
}
|
|
|
|
var value = options.Value;
|
|
return value.KnownProxies.Contains(ip) || value.KnownIPNetworks.Any(network => network.Contains(ip));
|
|
}
|
|
}
|