1

I would very much like to be able to set Azure API Policy attributes based on a User's Jwt Claims data. I have been able to set string values for things like the counter-key and increment-condition but I can't set all attributes. I imagined doing something like the following:

<rate-limit-by-key 
   calls="@((int) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/LimitRate/Limit", "5"))" 
   renewal-period="@((int) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/LimitRate/Duration/InSeconds", "60"))" 
   counter-key="@((string)context.Variables["Subject"])" 
   increment-condition="@(context.Response.StatusCode == 200)"
/>

However there seems to be some validation happening when I save the policy as I get the following error:

Error in element 'rate-limit-by-key' on line 98, column 10: The 'calls' attribute is invalid - The value '@((int) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/LimitRate/Limit", "5"))' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:int' - The string '@((int) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/LimitRate/Limit", "5"))' is not a valid Int32 value.

I even have trouble setting a string parameter (albeit one with a strict format)

<quota-by-key 
    calls="10"
    bandwidth="100" 
    renewal-period="@((string) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/Quota/RenewalPeriod", "P00Y00M01DT00H00M00S"))"
    counter-key="@((string)context.Variables["Subject"])"
/>

Which gives the following when I try and save the policy:

Error in element 'quota-by-key' on line 99, column 6: @((string) context.Variables["IdentityToken"].AsJwt().Claims.GetValueOrDefault("/Quota/RenewalPeriod", "P00Y00M01DT00H00M00S")) is not in a valid format. Provide number of seconds or use 'PxYxMxDTxHxMxS' format where 'x' is a number.

I have tried a large set of variations casting, Convert.ToInt32, claims that are not strings, @{return 5}, @(5) etc but there seems to be some validation happening at save time that is stopping it.

Is there away around this issue as I think it would be a useful feature to add to my API?

2 Answers2

3

calls attribute on rate-limit-by-key and quota-by-key does not support policy expressions. Internal limitations block us from treating it on per-request basis unfortunately. The best you can do is categorize requests into a few finite groups and apply rate limit/quota conditionally using choose policy.

Or try using increment-count attribute to control by how much counter is increased per each request.

Vitaliy Kurokhtin
  • 7,205
  • 1
  • 19
  • 18
0

enter image description here

Please look at the Azure APIM documentation and they have mentioned it as Policy expressions are allowed on the Calls attribute