問題描述
在通過REST API的方式來管理APIM資源,需要調用Azure提供的management接口。而這所有的接口,都是需要有Token並且還需要正確的Token。如若不然,就會獲取到如下的錯誤:
{
"error": {
"code": "AuthenticationFailed",
"message": "Authentication failed. The 'Authorization' header is missing."
}
}
OR
{ "error": { "code": "AuthenticationFailed", "message": "Authentication failed." } }
如在官方對API調用的介紹中,都是需要設置 Authorization 。
缺少Token和Token錯誤的截圖(使用Postman測試調用Get APIM API List的接口:GET https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis?api-version=2019-12-01)
本文就從 快速獲取Token 和 通過AAD Authorization URL獲取Token 兩種方式進行介紹。
問題解決
方式一: 快速的從Azure APIM門戶中獲取Token
PS: 這個方式適用於驗證Azure Management的調用方式,或一次性調用等場景。使用的Token權限能力由當前登錄Azure門戶的用戶的權限所決定
1)登錄Azure門戶,打開API Management服務並選中其中需要操作的APIM對象。
2)點擊F12,打開瀏覽器的開發者模式,進入Networking選項卡
3)刷新頁面,在所有請求列表中搜索“ management.chinacloudapi.cn ”,篩選目標請求
4)在請求的 Request Body 中發現 Authorization 值。
演示動畫:
方式二: 通過AAD Authorization URL獲取Token
PS:此種方式為正確的調用方式,通過發送POST請求獲取Token。可以在Coding中長期使用。由在AAD:Azure Active Directory中所使用的服務主體權限所決定。
1)登錄Azure 門戶,進入AAD頁面,選中“ App Registrations ”,然后點擊“ + New registration ”按鈕
2)輸入新注冊應用的名稱 “ apimDevOpsUser ”,點擊“ Register ”按鈕。注冊成功后,保存下“Tenant”和“Application”值。
3)設置應用客戶端密碼。選擇 “ Certificates & secrets ” 目錄,點擊“ + New client secret ”按鈕,根據提示生產新密鑰,然后復制出來保存(PS: 此處的密鑰只有第一次創建時可見,此后全是*號代替,所以務必保存下來)
4)回到APIM資源的權限設定頁面(IAM), 為新的注冊應用賦予 Contributor 權限。(可根據具體需要賦予權限)
6)在Postman中使用POST方式調用接口:https://login.chinacloudapi.cn/{{TENANT}}/oauth2/v2.0/token
Request Type: POST Request URL: https://login.chinacloudapi.cn/{{TENANT}}/oauth2/v2.0/token Request Body: tenant:{{TENANT}} client_id:{{CLIENT}} scope:https://management.chinacloudapi.cn/.default grant_type:client_credentials client_secret:{{SECRETS}}
PS: scope是非常重要的一個參數,如APIM資源的API的URL為"https://management.chinacloudapi.cn/subscriptions/{...",所以正確的SCOPE是“ https://management.chinacloudapi.cn/.default ”
7) 發送請求,獲取正確的Token。
演示動畫:
獲取Token后的正確調用截圖:
GET https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis?api-version=2019-12-01 Authorization: Bearer ....................
參考資料
APIM REST API Document : Apis - Get -- https://docs.microsoft.com/en-us/rest/api/apimanagement/2019-12-01/apis/get