【Azure API 管理】APIM如何实现对部分固定IP进行访问次数限制呢?如60秒10次请求

APIM,IP,访问,部分 · 浏览次数 : 180

小编点评

**重要:** - Policy elements can appear only within the <inbound>, <outbound>, <backend> section elements. - To apply a policy to the incoming request (before it is forwarded to the backend service), place a corresponding policy element within the <inbound> section element. - To apply a policy to the outgoing response (before it is sent back to the caller), place a corresponding policy element within the <outbound> section element. - To add a policy, place the cursor at the desired insertion point and select a policy from the sidebar. - To remove a policy, delete the corresponding policy statement from the policy document. - Position the <base> element within a section element to inherit all policies from the corresponding section element in the enclosing scope. - Remove the <base> element to prevent inheriting policies from the corresponding section element in the enclosing scope. - Policies are applied in the order of their appearance, from the top down.

正文

问题描述

使用Azure API Management, 想对一些固定的IP地址进行访问次数的限制,如被限制的IP地址一分钟可以访问10次,而不被限制的IP地址则可以无限访问?

 

ChatGPT 解答

最近ChatGPT爆火,所以也把这个问题让ChatGPT来解答,然后人工验证它的回答正确与否?

根据对APIM Policy的文档参考, choose 和 rate-limit 策略组合理论上的确可以实现要求, 接下来就让我们实际验证:

 

验证步骤

1)在API的Inbound 策略中添加 choose策略

(策略具体内容,见文末)

2) 测试验证,连续对该API访问10次以上,得到429 Too Many Requests错误

3)以上证明,ChatGPT针对这个问题的解答是正确的!

 

工程师解答

在参考ChatGPT给出的 choose + rate limit 组合后,我们也发现另一个选项。使用 rate-limit-by-key 策略实现对特定IP的速率限制。

  • rate-limit-by-key 策略https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#LimitCallRateByKey , 可以对调用速率进行限制,使指定时段的调用不超出指定的数目,避免单个密钥的 API 使用量暴增。 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。 可以添加可选增量条件,指定在决定是否到达限制值时应该进行计数的请求。 超过此调用速率时,调用方会收到 429 Too Many Requests 响应状态代码。

在官方文档中给出的示例中,是针对所有的IP(context.Request.IpAddress)都进行了10次/60秒请求的限制,而本示例中则特指“某些固定IP”限制。那么如何来完成这个需求呢?

答案 就在“rate-limit-by-key 策略”的说明中,”可以添加可选增量条件,指定在决定是否到达限制值时应该进行计数的请求”, 所以,只要可选增量条件(increment-condition) 的值根据输入的IP地址动态赋值True/False, 就能完美匹配以上要求。

 

理论推断,只需要实现如下逻辑,即可以实现终极需求“想对一些固定的IP地址进行访问次数的限制,如被限制的IP地址一分钟可以访问10次,而不被限制的IP地址则可以无限访问?

只需两步:

1)通过设置一个变量(set-variable) 值,用C#代码来计算变量值,在赋值语句中,预先定义一个IP限制列表,通过 contains 检查当前请求IP是否在列表中,返回True or False 。True表示当前请求的IP需要速率限制, 否则,不需要。

2) 然后,在rate-limit-by-key 的 increment-condition条件中使用上一步参数值,进行判断是否计入限制

验证步骤

1)在API的 Inbound 策略中添加 rate-limit-by-key策略

(策略具体内容,见文末)

 

2)验证在30秒,访问5次以上后,同样得到429 Too Many Requests错误

 

3) 当在请求Headers中添加Ocp-Apim-Trace: true 和 Ocp-Apim-Subscription-Key: {订阅Key}后,可以查看请求在APIM中执行的日志跟踪。可以查看rate-limit-by-key 策略的执行情况.

 

总结

想实现固定IP地址访问次数的限制,至少有如下两种解决方案。

方案一:Choose + rate-limit 策略组合

<!--
    IMPORTANT:
    - Policy elements can appear only within the <inbound>, <outbound>, <backend> section elements.
    - To apply a policy to the incoming request (before it is forwarded to the backend service), place a corresponding policy element within the <inbound> section element.
    - To apply a policy to the outgoing response (before it is sent back to the caller), place a corresponding policy element within the <outbound> section element.
    - To add a policy, place the cursor at the desired insertion point and select a policy from the sidebar.
    - To remove a policy, delete the corresponding policy statement from the policy document.
    - Position the <base> element within a section element to inherit all policies from the corresponding section element in the enclosing scope.
    - Remove the <base> element to prevent inheriting policies from the corresponding section element in the enclosing scope.
    - Policies are applied in the order of their appearance, from the top down.
    - Comments within policy elements are not supported and may disappear. Place your comments between policy elements or at a higher level scope.
-->
<policies>
    <inbound>
        <base />
        <set-variable name="IsCountIpLimit" value="@{
                string ipAddress =context.Request.IpAddress; 

                List<string> cidrList = new List<string>(){
                    "167.xxx. xxx.135",
                    "167.xxx. xxx.136",
                    "167.xxx. xxx.137"
                };
                return cidrList.Contains(ipAddress);
                }" />
        <choose>
            <when condition="@((bool)context.Variables["IsCountIpLimit"])">
                <rate-limit calls="10" renewal-period="60" />
            </when>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

 

方案二:rate-limit-by-key策略

<!--
    IMPORTANT:
    - Policy elements can appear only within the <inbound>, <outbound>, <backend> section elements.
    - To apply a policy to the incoming request (before it is forwarded to the backend service), place a corresponding policy element within the <inbound> section element.
    - To apply a policy to the outgoing response (before it is sent back to the caller), place a corresponding policy element within the <outbound> section element.
    - To add a policy, place the cursor at the desired insertion point and select a policy from the sidebar.
    - To remove a policy, delete the corresponding policy statement from the policy document.
    - Position the <base> element within a section element to inherit all policies from the corresponding section element in the enclosing scope.
    - Remove the <base> element to prevent inheriting policies from the corresponding section element in the enclosing scope.
    - Policies are applied in the order of their appearance, from the top down.
    - Comments within policy elements are not supported and may disappear. Place your comments between policy elements or at a higher level scope.
-->
<policies>
    <inbound>
        <base />
        <set-variable name="IsCountIpLimit" value="@{
                string ipAddress =context.Request.IpAddress; 

                List<string> limitIPs = new List<string>(){
                    "167.xxx. xxx.135",
                    "167.xxx. xxx.136",
                    "167.xxx. xxx.137"
                };

                return limitIPs.Contains(ipAddress);
                }" />
        <rate-limit-by-key calls="5" renewal-period="30" counter-key="@(context.Request.IpAddress)" increment-condition="@(context.Response.StatusCode >= 200 && context.Response.StatusCode < 300 && (bool)context.Variables["IsCountIpLimit"])" />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

 

 

参考资料

choose策略https://docs.azure.cn/zh-cn/api-management/api-management-advanced-policies#choose 

rate-limit策略https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#LimitCallRate ,

rate-limit-by-key 策略https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#LimitCallRateByKey 

 

与【Azure API 管理】APIM如何实现对部分固定IP进行访问次数限制呢?如60秒10次请求相似的内容:

【Azure API 管理】APIM如何实现对部分固定IP进行访问次数限制呢?如60秒10次请求

问题描述 使用Azure API Management, 想对一些固定的IP地址进行访问次数的限制,如被限制的IP地址一分钟可以访问10次,而不被限制的IP地址则可以无限访问? ChatGPT 解答 最近ChatGPT爆火,所以也把这个问题让ChatGPT来解答,然后人工验证它的回答正确与否? 根据

【Azure API 管理】APIM中证书更新问题

问题描述 每一年到期更新域名证书,APIM会中断服务,请问如何不中断服务? 问题解答 Azure API 管理允许在受信任的根证书和中间证书存储中的计算机上安装 CA 证书,分配证书的过程可能需要 15 分钟或更久,这取决于部署规模。 开发人员 SKU 在此过程中有停机时间。 基本 SKU 和更高级

【Azure API 管理】Azure APIM服务集成在内部虚拟网络后,在内部环境中打开APIM门户使用APIs中的TEST功能失败

问题描述 使用微软API管理服务(Azure API Management),简称APIM。 因为公司策略要求只能内部网络访问,所以启用了VNET集成。集成方式见: (在内部模式下使用 Azure API 管理连接到虚拟网络:https://docs.azure.cn/zh-cn/api-manag

【Azure API Management】实现在API Management服务中使用MI(管理标识 Managed Identity)访问启用防火墙的Storage Account

问题描述 在Azure的同一数据中心,API Management访问启用了防火墙的Storage Account,并且把APIM的公网IP地址设置在白名单。但访问依旧是403 原因是: 存储帐户部署在同一区域中的服务使用专用的 Azure IP 地址进行通信。 因此,不能基于特定的 Azure 服

【Azure 应用服务】调用Azure REST API来获取 App Service的访问限制信息(Access Restrictions)以及修改

问题描述 昨天的博文中(https://www.cnblogs.com/lulight/p/17099179.html)介绍了使用Python SDK 来获取App Service的访问限制信息,那么如何调用REST API来实现呢? 问题解答 如大家所知,Azure 不管是SDK, 门户UI,或者

【Azure 存储服务】使用REST API操作Azure Storage Table,删除数据(Delete Entity)

问题描述 使用Azure Storage Table的REST API,实现根据过滤条件删除满足条件的数据,调用方法为 Delete Entity (Azure Storage) 问题实现 第一步:通过Azure Stroage 门户或者是其他工具(如:Azure Storage Explorer)

【Azure Developer】如何通过Azure Portal快速获取到对应操作的API并转换为Python代码

问题描述 对于Azure资源进行配置操作,门户上可以正常操作。但是想通过Python代码实现,这样可以批量处理。那么在没有SDK的情况下,是否有快速办法呢? 问题解答 当然可以,Azure Portal上操作的所有资源都是通过REST API来实现的,所以只要找到正确的API,就可以通过浏览器中抓取

【Azure 存储服务】记一次调用Storage Blob API使用 SharedKey Authorization出现的403错误

问题描述 使用Azure Storag Blob REST API上传文件,用SharedKey作为Authorization出现403错误。 错误消息 b'\xef\xbb\xbfAuthenti

【Azure Developer】使用 Microsoft Graph API查看用户状态和登录记录

问题描述 通过Microsoft Graph的API如何来查看用户信息和登录记录呢? 问题解答 第一步:需要一个授权Token 比如一个拥有查看用户权限的Azure账号,通过Azure CLI 命令获取到一个Access Token az cloud set --name AzureChinaClo

【Azure Developer】使用 Microsoft Graph API 获取 AAD User 操作示例

问题描述 查看官方文档“ Get a user ” , 产生了一个操作示例的想法,在中国区Azure环境中,演示如何获取AAD User信息。 问题解答 使用Microsoft Graph API,演示如何获取AAD User信息,因参考文档是针对Global Azure,所以文档种的URL为: /