【Azure API 管理】APIM如何實(shí)現(xiàn)對(duì)部分固定IP進(jìn)行訪問次數(shù)限制呢?如60秒10次請(qǐng)求

問題描述

使用Azure API Management, 想對(duì)一些固定的IP地址進(jìn)行訪問次數(shù)的限制欢策,如被限制的IP地址一分鐘可以訪問10次黄鳍,而不被限制的IP地址則可以無(wú)限訪問?


image.png

ChatGPT 解答

最近ChatGPT爆火窃款,所以也把這個(gè)問題讓ChatGPT來(lái)解答课兄,然后人工驗(yàn)證它的回答正確與否?


image.png

根據(jù)對(duì)APIM Policy的文檔參考晨继, choose 和 rate-limit 策略組合理論上的確可以實(shí)現(xiàn)要求, 接下來(lái)就讓我們實(shí)際驗(yàn)證:

驗(yàn)證步驟

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


image.png

(策略具體內(nèi)容屿聋,見文末)

  1. 測(cè)試驗(yàn)證,連續(xù)對(duì)該API訪問10次以上藏鹊,得到429 Too Many Requests錯(cuò)誤


    image.png

3)以上證明润讥,ChatGPT針對(duì)這個(gè)問題的解答是正確的!

工程師解答

在參考ChatGPT給出的 choose + rate limit 組合后盘寡,我們也發(fā)現(xiàn)另一個(gè)選項(xiàng)楚殿。使用 rate-limit-by-key 策略實(shí)現(xiàn)對(duì)特定IP的速率限制。

  • rate-limit-by-key 策略https://docs.azure.cn/zh-cn/api-management/api-management-access-restriction-policies#LimitCallRateByKey 竿痰, 可以對(duì)調(diào)用速率進(jìn)行限制脆粥,使指定時(shí)段的調(diào)用不超出指定的數(shù)目,避免單個(gè)密鑰的 API 使用量暴增影涉。 密鑰的值可以是任意字符串冠绢,通常使用策略表達(dá)式來(lái)提供密鑰。 可以添加可選增量條件常潮,指定在決定是否到達(dá)限制值時(shí)應(yīng)該進(jìn)行計(jì)數(shù)的請(qǐng)求弟胀。 超過(guò)此調(diào)用速率時(shí),調(diào)用方會(huì)收到 429 Too Many Requests 響應(yīng)狀態(tài)代碼。

在官方文檔中給出的示例中孵户,是針對(duì)所有的IP(context.Request.IpAddress)都進(jìn)行了10次/60秒****請(qǐng)求的限制萧朝,而本示例中則特指“某些固定IP”限制。那么如何來(lái)完成這個(gè)需求呢夏哭?

image.png

答案 就在“rate-limit-by-key 策略”的說(shuō)明中检柬,”可以添加可選增量條件,指定在決定是否到達(dá)限制值時(shí)應(yīng)該進(jìn)行計(jì)數(shù)的請(qǐng)求”, 所以竖配,只要可選增量條件(increment-condition) 的值根據(jù)輸入的IP地址動(dòng)態(tài)賦值True/False何址, 就能完美匹配以上要求。

image.png

理論推斷进胯,只需要實(shí)現(xiàn)如下邏輯用爪,即可以實(shí)現(xiàn)終極需求“想對(duì)一些固定的IP地址進(jìn)行訪問次數(shù)的限制,如被限制的IP地址一分鐘可以訪問10次胁镐,而不被限制的IP地址則可以無(wú)限訪問偎血?

只需兩步:

1)通過(guò)設(shè)置一個(gè)變量(set-variable) 值,用C#代碼來(lái)計(jì)算變量值盯漂,在賦值語(yǔ)句中颇玷,預(yù)先定義一個(gè)IP限制列表,通過(guò) contains 檢查當(dāng)前請(qǐng)求IP是否在列表中就缆,返回True or False 帖渠。True表示當(dāng)前請(qǐng)求的IP需要速率限制, 否則,不需要竭宰。

2) 然后空郊,在rate-limit-by-key 的 increment-condition條件中使用上一步參數(shù)值,進(jìn)行判斷是否計(jì)入限制

驗(yàn)證步驟

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


image.png

(策略具體內(nèi)容羞延,見文末)

2)驗(yàn)證在30秒,訪問5次以上后脾还,同樣得到429 Too Many Requests錯(cuò)誤


image.png
  1. 當(dāng)在請(qǐng)求Headers中添加Ocp-Apim-Trace: true 和 Ocp-Apim-Subscription-Key: {訂閱Key}后伴箩,可以查看請(qǐng)求在APIM中執(zhí)行的日志跟蹤”陕可以查看rate-limit-by-key 策略的執(zhí)行情況.


    image.png

總結(jié)

想實(shí)現(xiàn)固定IP地址訪問次數(shù)的限制嗤谚,至少有如下兩種解決方案。

方案一: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

當(dāng)在復(fù)雜的環(huán)境中面臨問題巩步,格物之道需:濁而靜之徐清,安以動(dòng)之徐生桦踊。 云中椅野,恰是如此!

分類: 【Azure API 管理】

標(biāo)簽: rate-limit-by-key , Azure API 管理 , 429 Too Many Requests , 實(shí)現(xiàn)對(duì)部分固定IP進(jìn)行訪問次數(shù) , Choose + rate limit

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子竟闪,更是在濱河造成了極大的恐慌离福,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件炼蛤,死亡現(xiàn)場(chǎng)離奇詭異妖爷,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)理朋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門絮识,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人嗽上,你說(shuō)我怎么就攤上這事次舌。” “怎么了炸裆?”我有些...
    開封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵垃它,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我烹看,道長(zhǎng)国拇,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任惯殊,我火速辦了婚禮酱吝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘土思。我一直安慰自己务热,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開白布己儒。 她就那樣靜靜地躺著崎岂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪闪湾。 梳的紋絲不亂的頭發(fā)上冲甘,一...
    開封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音途样,去河邊找鬼江醇。 笑死,一個(gè)胖子當(dāng)著我的面吹牛何暇,可吹牛的內(nèi)容都是我干的陶夜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼裆站,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼条辟!你這毒婦竟也來(lái)了黔夭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤捂贿,失蹤者是張志新(化名)和其女友劉穎纠修,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體厂僧,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡扣草,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了颜屠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辰妙。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖甫窟,靈堂內(nèi)的尸體忽然破棺而出密浑,到底是詐尸還是另有隱情,我是刑警寧澤粗井,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布尔破,位于F島的核電站,受9級(jí)特大地震影響浇衬,放射性物質(zhì)發(fā)生泄漏懒构。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一耘擂、第九天 我趴在偏房一處隱蔽的房頂上張望胆剧。 院中可真熱鬧,春花似錦醉冤、人聲如沸秩霍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)铃绒。三九已至,卻和暖如春螺捐,著一層夾襖步出監(jiān)牢的瞬間颠悬,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工归粉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留椿疗,地道東北人漏峰。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓糠悼,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親浅乔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子倔喂,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容