我正在尝试以编程方式获取 Azure 数据工厂的托管标识对象(使用 Python)。
为此,我按照以下步骤操作:
- 在 Azure Active Directory 中注册应用以获取客户端 ID、添加客户端 key 、租户 ID、范围。
- 按照以下链接中的步骤获取 #1 中注册应用程序的访问 token : https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/sample/confidential_client_secret_sample.py
- 将已注册的应用添加到数据工厂订阅,并以“所有者”角色
- 使用以下代码:
head = {"Authorization": "Bearer {}".format(request_token)}
#request_token is the access token from #2
requests.get('https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}?api-version=2018-06-01', headers = head)
如链接中提供的: https://learn.microsoft.com/en-us/azure/data-factory/data-factory-service-identity
执行这些步骤后,#5 的响应是 error="invalid_token", error_description="无法找到访问 token 的身份。"
应用程序注册没有用于检查托管身份的身份部分。
我是否遗漏了任何步骤?
请找到下面的代码。感谢您的宝贵时间!
import sys
import json
import logging
import requests
import msal
input_client_id = <client_id>
input_authority = "https://login.microsoftonline.com/<tenant_id>"
input_secret = <client_Secret>
input_scope = ["https://graph.microsoft.com/.default"]
input_endpoint = "https://graph.microsoft.com/v1.0/applications"
app = msal.ConfidentialClientApplication(
input_client_id, authority=input_authority,
client_credential=input_secret,
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
)
result = app.acquire_token_for_client(scopes=input_scope)
print('Access Token', result['access_token'])
request_token = result['access_token']
head = {"Authorization": "Bearer {}".format(request_token)}
response = requests.get('{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}?api-version=2018-06-01', headers=head)
部分错误响应:
{'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Content-Type': 'application/json; charset=utf-8', 'Expires': '-1', 'WWW-Authenticate': 'Bearer authorization_uri="https://login.windows.net/<tenant_id>", error="invalid_token", error_description="Could not find identity for access token."'
最佳答案
尝试将范围 https://graph.microsoft.com/.default
替换为 https://management.azure.com/.default
。
当您请求 azure 管理 Rest API 时,您需要此范围。
关于Azure 托管标识错误 - 找不到访问 token 的标识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65918966/