【发布时间】:2020-09-11 23:26:56
【问题描述】:
我有一个 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 模块的一些东西?
【问题讨论】:
标签: python azure-functions msal azure-monitoring azure-managed-identity