如何使用服务主体和Python SDK向Azure进行身份验证?

时间:2020-05-27 18:06:44

标签: python azure azure-active-directory

我目前正在尝试使用azure-mgmt-support MicrosoftSupport客户端向Azure进行身份验证,并收到以下错误:

AdalError: Get Token request returned http error: 400 and server response: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier 'xxx' was not found in the directory 'management.core.windows.net'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.

我已经仔细检查过,肯定使用了正确的client_idtenant_id。我在这里想念什么?我的代码如下:

from azure.mgmt.support import MicrosoftSupport
from msrestazure.azure_active_directory import ServicePrincipalCredentials 

sub_id = 'xxx'
sp_creds = ServicePrincipalCredentials(client_id='xxx', secret='xxx')

SupportClient = MicrosoftSupport(sp_creds, sub_id)

1 个答案:

答案 0 :(得分:0)

走了一会儿,又看了一下文档,发现了我的错误-我从tenant_id对象中丢失了ServicePrincipalCredentials。不明显的是from the SDK specification或错误消息,这是缺少的,因为唯一需要的变量是client_idsecret,但是当我查看this example in the documentation时,我意识到它丢失了(为方便起见,请在下面粘贴代码,以防文档页面更改)。

import os
from azure.mgmt.resource import SubscriptionClient
from azure.common.credentials import ServicePrincipalCredentials

# Retrieve the IDs and secret to use with ServicePrincipalCredentials
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
tenant_id = os.environ["AZURE_TENANT_ID"]
client_id = os.environ["AZURE_CLIENT_ID"]
client_secret = os.environ["AZURE_CLIENT_SECRET"]

credential = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)

subscription_client = SubscriptionClient(credential)

subscription = next(subscription_client.subscriptions.list())
print(subscription.subscription_id)