It is easy to rate limit the api by using,
<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Subscription.Id)" />
But i need to rate limit the api by using a apiKey send as a request parameter.
It is easy to rate limit the api by using,
<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Subscription.Id)" />
But i need to rate limit the api by using a apiKey send as a request parameter.
First, I assume from your example that you want to specify an element of the request itself as the counter-key
instead of the subscription ID (as shown in your example). If that's correct, then...
The docs give the following example of using a policy expression to specify the 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>
Assuming the API Key you mention is something that would be passed in as a request header, looks like you would be able to do the following:
<rate-limit-by-key counter-key='@(context.Request.Headers.TryGetValue("YourApiKey"))' ... />
Looks like you can use a multi-line policy expression if you want to handle the case of the ApiKey not being included in the request at all:
<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;
}'
...
/>
NOTE: I haven't tested any of the suggested policies here, but I think the last one here would allow 500 requests per period per {YourApiKey}
, and if the Api Key isn't supplied, no requests would be allowed.
Assuming that you are passing the api-key as a header (which is a best practice, source: Place API key in Headers or URL) the rate-limit should look like this:
<rate-limit-by-key calls="3" renewal-period="15" counter-key="@(context.Request.Headers.GetValueOrDefault("x-api-key", "default-value"))" />