繁体   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