如何通过使用自定义 apiKey(而不是 subscripon id)在 azure api 管理中使用速率限制?

问题描述 投票:0回答:2

通过使用可以轻松限制 api 的速率,

<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Subscription.Id)" />

但是我需要通过使用 apiKey 作为请求参数发送来限制 api 的速率。

azure azure-api-management
2个回答
0
投票

首先,我从您的示例中假设您希望将请求本身的一个元素指定为

counter-key
而不是订阅 ID(如示例中所示)。如果这是正确的,那么...

文档给出了以下使用策略表达式来指定

counter-key
的示例。

<policies>
    <inbound>
        <base />
        <rate-limit-by-key  calls="10"
              renewal-period="60"
              increment-condition="@(context.Response.StatusCode == 200)"
              counter-key="@(context.Request.IpAddress)"
              remaining-calls-variable-name="remainingCallsPerIP"/>
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

假设您提到的 API 密钥将作为请求标头传入,看起来您可以执行以下操作:

<rate-limit-by-key counter-key='@(context.Request.Headers.TryGetValue("YourApiKey"))' ... />

如果您想处理 ApiKey 根本不包含在请求中的情况,看起来您可以使用多行策略表达式:

<rate-limit-by-key 
  counter-key='@{
    if (context.Request.Headers.TryGetValue("YourApiKey", out value))
    {
      if(value != null && value.Length > 0)
      {
        return value;
      }
    }
    return null;
  }' 
  calls='@{
    if (context.Request.Headers.TryGetValue("YourApiKey", out value))
    {
      if(value != null && value.Length > 0)
      {
        return 500;
      }
    }
    return 0;
  }' 
  ... 
/>

注意:我没有在这里测试任何建议的策略,但我认为这里的最后一个策略将允许每个

{YourApiKey}
每个周期 500 个请求,如果未提供 Api 密钥,则不会允许任何请求.


0
投票

假设您将 api-key 作为标头传递(这是最佳实践,来源:将 API 密钥放在标头或 URL 中),速率限制应如下所示:

<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Request.Headers.GetValueOrDefault("x-api-key", "default-value"))" />
© www.soinside.com 2019 - 2024. All rights reserved.