簡體   English   中英

遷移 Python ADAL 自定義指標 Azure 函數以支持托管標識

[英]Migrate Python ADAL Custom Metrics Azure Function to support Managed Identity

我有一個 Python 函數,它使用使用 REST API https://docs.microsoft.com/en-us/azure/azure-monitor/platform/metrics-store-custom-rest-api將自定義指標發送到 Azure 的預覽選項,以前這是一個 C# 函數,其中授權和獲取不記名令牌是通過以下方式自動處理的:

var azureServiceTokenProvider = new AzureServiceTokenProvider();
string bearerToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://monitoring.azure.com/").ConfigureAwait(false);

當托管標識分配給函數時,這在使用登錄用戶的 VS Code 和 Azure 中起作用。

我需要將其轉換為 Python,但到目前為止我能想到的最好的(工作)是:

import logging, requests, os, adal
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    regional_monitoring_url = "https://eastus.monitoring.azure.com"
    monitored_resource_id = os.environ['RESOURCE_ID']
    full_endpoint = f"{regional_monitoring_url}{monitored_resource_id}/metrics"

    tenant_id = os.environ['AZURE_TENANT_ID']
    context = adal.AuthenticationContext(f'https://login.microsoftonline.com/{tenant_id}')
    token = context.acquire_token_with_client_credentials("https://monitoring.azure.com/", os.environ['AZURE_CLIENT_ID'], os.environ['AZURE_CLIENT_SECRET']    )
    bearer_token = token['accessToken']

    json = req.get_json()
    headers = {"Authorization": 'Bearer ' + bearer_token}
    result = requests.post(url = full_endpoint, headers = headers, json = json)

    return func.HttpResponse(f"Done - {result.status_code} {result.text}", status_code=200)

這顯然依賴於我創建具有相關權限的服務主體。 我正在嘗試研究如何使用 C# 庫具有的自動托管身份授權。

我知道 ADAL 應該被 MSAL 取代,但我無法弄清楚它如何/是否自動處理托管身份,所以我嘗試了 azure-identity:

from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
token = credential.get_token("https://monitoring.azure.com/.default")
bearer_token = token.token

這給了我一個令牌,但因為它需要一個范圍而不是資源,這意味着將 .default 添加到資源 URL,當我將承載令牌發送到監控端點時,它抱怨資源不匹配並且必須完全是“https” ://monitoring.azure.com/"

這目前是不可能的,還是我遺漏了 azure-identity 或 MSAL Python 模塊?

根據我的研究,當請求 Azure AD 令牌以發出自定義指標時,請確保請求令牌的受眾是https://monitoring.azure.com/ 有關詳細信息,請參閱此處 所以我們應該將范圍更新為https://monitoring.azure.com//.default 在此處輸入圖片說明

例如

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    credential = DefaultAzureCredential()
    token = credential.get_token("https://monitoring.azure.com//.default")
    bearer_token = token.token
    #full_endpoint=""
    json = req.get_json()
    headers = {"Authorization": 'Bearer ' + bearer_token}
    #result = requests.post(url = full_endpoint, headers = headers, json = json)
    return func.HttpResponse(f"Done - {bearer_token}", status_code=200)

在此處輸入圖片說明 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM