Adding IP address filtering to your C# YARP proxy
Posted: (EET/GMT+2)
I was today working on some YARP code and needed a simple way to be able to limit incoming HTTPS requests by their IP address. Since YARP uses a pipeline architecture, the solution is to add an async handler that checks the context's remote IP address, and rejects it if not part of an access list.
You get to also decide how the request is responded to: for instance, you could simple reply with HTTP 403 Forbidden, if the IP address is not on the allow list. Expressed in C#, this could look something like this:
proxyPipeline.Use(async (context, next) =>
{
var feature = context.GetReverseProxyFeature();
var routeConfig = feature.Route.Config;
if (routeConfig.Metadata?.TryGetValue(
"IpAllowList", out var allowList) == true)
{
var remoteIp = context.Connection.RemoteIpAddress;
if (remoteIp is null || !ClientIpIsAllowed(remoteIp, allowList))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
await context.Response.WriteAsync(
"Forbidden by proxy IP policy.");
return;
}
}
await next();
});
In Microsoft IIS, you have a similar option in the "IP Address and Domain Restrictions" module, which allows you to configure the allowed IP addresses, but also the way you want requests from non-valid IP addresses to be handled.