[英]Migrate Python ADAL Custom Metrics Azure Function to support Managed Identity
I have a Python function using the preview option of sending custom metrics to Azure using the REST API https://docs.microsoft.com/en-us/azure/azure-monitor/platform/metrics-store-custom-rest-api , previously this was a C# function where authorisation and getting a bearer token was handled automagically by:我有一个 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);
This worked in VS Code using the logged in user and in Azure when a Managed Identity was assigned to the Function.当托管标识分配给函数时,这在使用登录用户的 VS Code 和 Azure 中起作用。
I needed to convert this to Python but so far the best (working) I've been able to come up with is:我需要将其转换为 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)
This obviously relies on me creating a Service Principal with the relevant permissions.这显然依赖于我创建具有相关权限的服务主体。 I'm trying to work out how to use the automatic Managed Identity authorisation that the C# libraries have.我正在尝试研究如何使用 C# 库具有的自动托管身份授权。
I know ADAL should be replaced by MSAL but I can't work out how/if that automagically handles Managed Identities so I tried azure-identity:我知道 ADAL 应该被 MSAL 取代,但我无法弄清楚它如何/是否自动处理托管身份,所以我尝试了 azure-identity:
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
token = credential.get_token("https://monitoring.azure.com/.default")
bearer_token = token.token
This gets me a token but because it requires a scope rather than a resource, which means adding .default to the resource URL, when I send the bearer token to the monitoring endpoint it complains the resource doesn't match and must be exactly "https://monitoring.azure.com/"这给了我一个令牌,但因为它需要一个范围而不是资源,这意味着将 .default 添加到资源 URL,当我将承载令牌发送到监控端点时,它抱怨资源不匹配并且必须完全是“https” ://monitoring.azure.com/"
Is this just not currently possible or am I missing something with either azure-identity or the MSAL Python modules?这目前是不可能的,还是我遗漏了 azure-identity 或 MSAL Python 模块?
According to my research, when werequest an Azure AD token to emit custom metrics, ensure that the audience the token is requested for is https://monitoring.azure.com/ .根据我的研究,当请求 Azure AD 令牌以发出自定义指标时,请确保请求令牌的受众是https://monitoring.azure.com/ 。 For more details, please refer to here .有关详细信息,请参阅此处。 So we should update scope as https://monitoring.azure.com//.default
所以我们应该将范围更新为https://monitoring.azure.com//.default
For example例如
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.