2

Currently, I'm using docker-compose to build my microservices. Every request that comes to API needs to go through the gateway service using Ocelot. In the gateway service, I have configured to restrict the number of requests. The documentation said that it limits based on the request IP address. However, when I tested, the IP shown always be docker's (172.x.x.x) so how can I test this function? I would like to test it's limits, and change the IP address in order to pass the limit blocker.

Thanks in advance.

Gateway config

"RateLimitOptions": {
        "ClientWhitelist": [],
        "EnableRateLimiting": true,
        "Period": "100s",
        "PeriodTimespan": 100,
        "Limit": 1
      },

Written IP in console

public static string GetIpAddress(this HttpContext httpContext)
{
     if (httpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
         return httpContext.Request.Headers["X-Forwarded-For"];
     else
         return httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
}

The result shown (before & after using VPN are the same)

172.19.0.7
TrungPhan
  • 21
  • 2

1 Answers1

0

By default, asp-net core only respects X-Forwarded headers if the request came from a local address. For example if IIS was acting as a reverse proxy on the same host.

You may need to configure ForwardedHeadersOptions, either explicitly as per the docs;

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;
    options.KnownProxies.Add(IPAddress.Parse("127.0.10.1"));
    options.ForwardedForHeaderName = "X-Forwarded-For-My-Custom-Header-Name";
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

...

app.UseForwardedHeaders();

Or perhaps, via appsettings.json;

services.Configure<ForwardedHeadersOptions>(configuration.GetSection("Forwarded"));

The middleware should then populate the HttpContext.Connection.RemoteIpAddress as if the client had connected directly to your server.

Jeremy Lakeman
  • 9,515
  • 25
  • 29
  • Hi, I've put those configs to the gateway service. However, when I log the RemoteIpAddress out, it is still the same (::ffff:172.28.0.1) no matter I'm using VPN or manual proxy – TrungPhan Jan 24 '22 at 07:31
  • So that's an IPv6 address, did you add it as a known proxy? – Jeremy Lakeman Jan 24 '22 at 10:07