Azure 托管标识错误 - 找不到访问令牌的标识

时间:2021-01-27 12:14:44

标签: azure azure-active-directory azure-managed-identity

我正在尝试以编程方式(使用 Python)获取 Azure 数据工厂的托管标识对象。

为此,我遵循以下步骤:

  1. 在 Azure Active Directory 中注册应用以获取客户端 ID、添加客户端机密、租户 ID、范围。
  2. 按照以下链接中的步骤获取 #1 中已注册应用的访问令牌: https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/sample/confidential_client_secret_sample.py
  3. 将注册的应用添加到数据工厂订阅中,角色为“所有者”
  4. 使用以下代码:
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://docs.microsoft.com/en-us/azure/data-factory/data-factory-service-identity

执行这些步骤后,#5 的响应是 error="invalid_token", error_description="无法找到访问令牌的身份。"

应用注册没有用于检查托管身份的身份部分。

我在这里遗漏了任何步骤吗?

请在代码下方找到。感谢您的时间!

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."'

1 个答案:

答案 0 :(得分:0)

尝试将范围 https://graph.microsoft.com/.default 替换为 https://management.azure.com/.default

当您请求 Azure 管理 Rest API 时,您需要此范围。