我尝试使用Azure AD进行身份验证以访问Azure Insights REST API,以便最终访问Azure Web应用程序。但是,the authentication example in their documentation仅限于C#和PowerShell。我正在尝试做同样的事情,但使用Python请求库。这是我到目前为止所得到的,但我找不到“未找到的”#404;回复。关于如何使用Python请求库对Insights API进行身份验证的任何想法?
AUTH = 'https://login.windows.net/%s' % TENANT_ID
RESOURCE = 'https://management.azure.com/'
def auth():
s = requests.Session()
params = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_KEY,
'resource': RESOURCE
}
response = s.post(AUTH, params=params)
print response.url
print response.status_code
print response.reason
auth()
编辑1:
更新的身份验证网址修复了它。谢谢。但是,我仍然希望专门使用Python请求库来获取Web应用程序/资源组。
RESOURCE_VERSION = '2015-01-01'
RESOURCE_URI = 'https://management.azure.com/subscriptions/%s/resourcegroups' % (SUBSCRIPTION_ID)
s = requests.Session()
payload = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_KEY,
'resource': RESOURCE
}
response = s.post(AUTHENTICATION_CONTEXT, data=payload).json()
access_token = response['access_token']
s.headers = {
'Authorization': 'Bearer %s' % access_token,
'Content-Type': 'application/json'
}
s.params = {
'api-version': RESOURCE_VERSION
}
response2 = s.get(RESOURCE_URI).json()
print response2
这给了我以下输出
{u'error': {u'message': u"The client 'CLIENT_ID' with object id 'OBJECT_ID' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/read' over scope '/subscriptions/SUBSCRIPTION_ID'.", u'code': u'AuthorizationFailed'}}
基于响应,似乎它可能是我的Azure应用程序中的权限问题,但我已经为应用程序提供了我认为必须拥有的所有权限,它仍然给我相同的错误消息。
答案 0 :(得分:1)
身份验证端点不完整。在.Net中,它包含在.Net SDK中,身份验证令牌的完整端点如下所示:https://login.microsoftonline.com/<tenant_id>/oauth2/token
以下是代码段:
from azure.mgmt.common import SubscriptionCloudCredentials
from azure.mgmt.resource import ResourceManagementClient
import requests
def get_token_from_client_credentials(endpoint, client_id, client_secret):
payload = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'resource': 'https://management.core.windows.net/',
}
response = requests.post(endpoint, data=payload).json()
return response['access_token']
auth_token = get_token_from_client_credentials(
endpoint='https://login.microsoftonline.com/<tenant_id>/oauth2/token',
client_id='<client_id>',
client_secret='<client_secret>',
)
subscription_id = '<subscription_id>'
creds = SubscriptionCloudCredentials(subscription_id, auth_token)
resource_client = ResourceManagementClient(creds)
resource_group_list = resource_client.resource_groups.list(None)
rglist = resource_group_list.resource_groups
print rglist
您可以参考Resource Management Authentication了解更多信息。