Applying IP filter based on named value json in policy | Using LINQ query inside API management policy | Dynamically filtering IPs based on json
{tocify} $title={Table of Contents}
In this article we can see how to get NamedValue json content and load in JObject and use a LINQ query inside APIM policies for applying IP restriction in policy.
Also
refer part-I of this article here.
By
following this article from MSDN where we have when
conditions and Ip filter policies and advanced C# code inside policy can be
done.
First
create a Namedvalue inside Api Management under Namedvalues tab:
with
key name: IpAllowList value:
[
{
"User":"user1",
"subscriptionKey":"subskeyforuser1",
"AllowedIps" : ["192.168.1.3","192.168.1.4","192.168.1.5","192.168.3.4","13.91.284.72"]
}
]
To
get the Namedvalue Json content inside policy use the code below:
<set-variable name="IAllowListNamdval" value="{{IpAllowList}}" />
To
get the subscriptionkey given in the request header or parameter use the code below:
<set-variable name="SubscriptionKeyVar" value="@{ string[] value; string value2;
if (context.Request.Headers.TryGetValue("Ocp-Apim-Subscription-Key", out value))
{ if(value != null && value.Length > 0)
{
return value[0];
}
}
else if(context.Request.MatchedParameters.TryGetValue("Ocp-Apim-Subscription-Key", out value2))
{ if(value2 != null && value2 != "")
{
return value2;
}
}
return null;
}" />
Using
the LINQ query to the Json array obtained from Namedvalue see below code:
<set-variable name="AlwdIpForUser" value="@{
var jsonval = JArray.Parse((string)context.Variables.GetValueOrDefault<string>("IAllowListNamdval"));
var arr = jsonval.Where(m => m["subscriptionKey"].Value<string>() == (string)context.Variables.GetValueOrDefault<string>("SubscriptionKeyVar")).SelectMany(y => (JArray)y["AllowedIps"]);
return arr.Any(t => t.Value<string>() == (string)context.Request.IpAddress); }" />
Then
using the result in blocking the IP with below code:
<choose>
<when condition="@(!(bool)context.Variables.GetValueOrDefault<bool>("AlwdIpForUser"))">
<ip-filter action="forbid">
<address>@(context.Request.IpAddress)</address>
</ip-filter>
</when>
</choose>[
{
"User":"user1",
"subscriptionKey":"subskeyforuser1",
"AllowedIps" : ["192.168.1.3","192.168.1.4","192.168.1.5","192.168.3.4","13.91.284.72"]
}
]
By
following the above steps, we can filter and block IPs. In the Namedvalue we can
have Json content in this structure where user based on subscription key and
the corresponding IPs blocking can be applied.
Thanks 👍👌🙌