.NET 7 Azure Function 中的速率限制

huangapple go评论43阅读模式
英文:

.NET 7 Rate Limiting in Azure Function

问题

有没有办法在Azure Function v4(dotnet-isolated)的HttpTrigger上使用.NET 7的速率限制?

我已经像这样在我的ConfigureServices中添加了RateLimiter:

var builder = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(s =>
    {
        // ...
        
        s.AddRateLimiter(_ =>
        {
            _.AddPolicy("myfunction", httpContext =>
                RateLimitPartition.GetSlidingWindowLimiter(httpContext.Request.Headers["X-Forwarded-For"],
                _ => new SlidingWindowRateLimiterOptions
                {
                    AutoReplenishment = true,
                    PermitLimit = 1,
                    Window = TimeSpan.FromSeconds(5)
                }));
        });
    })
    .Build();

 [Function("myfunction")]
 [EnableRateLimiting("myfunction")]
 public async Task<IActionResult> MyFunction(
     [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req)
 { // ...
 }

我相当肯定它不应该像这样工作,但这只是为了举例情景。我的架构是Azure静态Web应用-->API管理(注意!消耗计划)-->Azure Function,并且我可以从Azure Function中的“X-Forwarded-For”标头获取有效的客户端IP,但是

因此,是否可能在函数级别对Azure Function应用速率限制策略?

谢谢!

英文:

Is there a way to use .NET 7 Rate Limiting on Azure Function v4 (dotnet-isolated) HttpTrigger?

I've added RateLimiter in my ConfigureServices like this:

var builder = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(s =&gt;
    {
        // ...
        
        s.AddRateLimiter(_ =&gt;
        {
            _.AddPolicy(&quot;myfunction&quot;, httpContext =&gt;
                RateLimitPartition.GetSlidingWindowLimiter(httpContext.Request.Headers[&quot;X-Forwarded-For&quot;],
                _ =&gt; new SlidingWindowRateLimiterOptions
                {
                    AutoReplenishment = true,
                    PermitLimit = 1,
                    Window = TimeSpan.FromSeconds(5)
                }));
        });
    })
    .Build();

and

 [Function(&quot;myfunction&quot;)]
 [EnableRateLimiting(&quot;myfunction&quot;)]
 public async Task&lt;IActionResult&gt; MyFunction(
     [HttpTrigger(AuthorizationLevel.Function, &quot;post&quot;, Route = null)] HttpRequestData req)
 { // ...
 }

I'm pretty sure it shouldn't even work like this, but just to give an example of the scenario. My architecture is Azure Static Web App --> API Management (NOTE! consumption plan) --> Azure Function, and I can get the valid client IP from the X-Forwarded-For header in the Azure Function, but

So, is it possible to apply the rate limiting policy to a Azure Function on a function level?

Thanks!

答案1

得分: 1

如 @Silent 提到的,您可以在 Azure APIM 消费计划中使用速率限制策略。

您可以将多个函数 API 导入到 Azure APIM 服务,并可以为每个 API 级别添加速率限制策略。
.NET 7 Azure Function 中的速率限制

我有消费计划的 APIM,我非常希望有一个基于 IP 而不是基于 API 的速率限制器,就像消费计划的 APIM 一样。

我理解您需要根据 IP 基础限制请求的数量。如果是的话,我们有"IP 地址限制"的概念,可以限制来自 IP 地址的请求/ API 调用,正如在MS Doc的速率限制策略中所述的自定义基于密钥的限制。

注意:

是的,rate-limit-by-key 在 APIM 消费计划中不可用。

英文:

As @Silent mentioned, you can use rate-limiting policy in Azure APIM Consumption Plan.

You can import multiple Function APIS to the Azure APIM Service and can add the Rate-limiting policy to each API Level.
.NET 7 Azure Function 中的速率限制

> I have consumption plan APIM, and I’d very much like to have a IP based rate limiter instead of API based, like it is with consumption plan APIM

I understand that you need to limit the number of requests per IP basis. If yes and this is the scenario, we have “IP address throttling” concept to limit the requests/API Calls from the IP address as mentioned in this MS Doc of Custom key-based throttling in Rate-limiting policy.

Note:

Yes, the rate-limit-by-key is not available in APIM Consumption Plan.

答案2

得分: 1

以下是翻译好的部分:

"Just [ported ThrottlingTroll to Azure Functions][1] (.NET 7 Isolated).

Works as an Azure Functions Middleware.

Supports

  • [ingress throttling][2] (returning 429 TooManyRequests or impeding
    responses from HTTP-triggered functions),
  • [egress throttling][3] (an
    HttpClient that limits itself) and
  • propagating 429 TooManyRequests
    [from egress to ingress][4].

Configurable [via host.json, programmatically or dynamically (by periodically reloading rate limits from whatever external config store without restarting the service)][5].

Stores counters in memory [or in a distributed cache][6].

Install from NuGet:
dotnet add package ThrottlingTroll.AzureFunctions
and then configure like this:


    workerAppBuilder.UseThrottlingTroll(hostBuilderContext, options =&gt;
    {
        options.Config = new ThrottlingTrollConfig
        {
            Rules = new[]
            {
                new ThrottlingTrollRule
                {
                    UriPattern = &quot;myfunction&quot;,

                    LimitMethod = new FixedWindowRateLimitMethod
                    {
                        PermitLimit = 1,
                        IntervalInSeconds = 5
                    },

                    // Identifying clients by their IP addresses
                    IdentityIdExtractor = request =&gt;
                    {
                        request.Headers.TryGetValue(&quot;x-forwarded-for&quot;, out var clientIpAddress);
                        return clientIpAddress;
                    }
                }
            }
        };
    });
});
```"

  [1]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#throttlingtrollazurefunctions
  [2]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-use-for-ingress-throttling
  [3]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-use-for-egress-throttling
  [4]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#to-propagate-from-egress-to-ingress
  [5]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-configure
  [6]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-specify-a-rate-counter-store-to-be-used

<details>
<summary>英文:</summary>

Just [ported ThrottlingTroll to Azure Functions][1] (.NET 7 Isolated).

Works as an Azure Functions Middleware.

Supports 

 - [ingress throttling][2] (returning `429 TooManyRequests` or impeding
   responses from HTTP-triggered functions),  
 - [egress throttling][3] (an
   HttpClient that limits itself) and  
 - propagating `429 TooManyRequests`
   [from egress to ingress][4].

Configurable [via host.json, programmatically or dynamically (by periodically reloading rate limits from whatever external config store without restarting the service)][5].

Stores counters in memory [or in a distributed cache][6].

Install from NuGet: 

dotnet add package ThrottlingTroll.AzureFunctions

and then configure like this:

builder.ConfigureFunctionsWorkerDefaults((hostBuilderContext, workerAppBuilder) => {

workerAppBuilder.UseThrottlingTroll(hostBuilderContext, options =&gt;
{
    options.Config = new ThrottlingTrollConfig
    {
        Rules = new[]
        {
            new ThrottlingTrollRule
            {
                UriPattern = &quot;myfunction&quot;,

                LimitMethod = new FixedWindowRateLimitMethod
                {
                    PermitLimit = 1,
                    IntervalInSeconds = 5
                },

                // Identifying clients by their IP addresses
                IdentityIdExtractor = request =&gt;
                {
                    request.Headers.TryGetValue(&quot;x-forwarded-for&quot;, out var clientIpAddress);
                    return clientIpAddress;
                }
            }
        }
    };
});

});


  [1]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#throttlingtrollazurefunctions
  [2]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-use-for-ingress-throttling
  [3]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-use-for-egress-throttling
  [4]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#to-propagate-from-egress-to-ingress
  [5]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-configure
  [6]: https://github.com/scale-tone/ThrottlingTroll/tree/main/ThrottlingTroll.AzureFunctions#how-to-specify-a-rate-counter-store-to-be-used

</details>



huangapple
  • 本文由 发表于 2023年2月14日 00:36:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定