Python 请求 - Azure RM API 返回 200 状态代码但内容为 400

Python Requests - Azure RM API returning 200 status code but 400 in content

我有一些代码试图针对 Azure 的资源管理器 REST 进行身份验证 API。

import json
import requests

tenant_id = "TENANT_ID"
app_id = "CLIENT_ID"
password = "APP_SECRET"

token_endpoint = 'http://login.microsoftonline.com/%s/oauth2/token' % tenant_id
management_uri = 'https://management.core.windows.net/'

payload = { 'grant_type': 'client_credentials',
            'client_id': app_id,
            'client_secret': password
}

auth_response = requests.post(url=token_endpoint, data=payload)
print auth_response.status_code
print auth_response.reason

这个returns:

200
OK

但是,当我打印 auth_response.content 或 auth_reponse.text 时,我得到了 400 HTML 错误代码和一条错误消息。

HTTP Error Code: 400
Sorry, but we’re having trouble signing you in. 
We received a bad request.

我能够使用 PostMan 取回正确的信息,但是,具有相同的 URI 和负载。我使用 Postman 中的 "Generate Code" 选项将我的请求导出到 Python 请求脚本并尝试了 运行。但是,我得到了同样的错误。

有人知道为什么会这样吗?

您应该为 token_endpoint 使用 HTTPS 而不是 HTTP,并且您还应该指定 API 版本。这是你应该使用的。

token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id

仅将您的 token_endpoint 修改为 https 协议。例如: token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id。 详情可参考https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx

同时,您可以利用 Microsoft Azure Active Directory Authentication Library (ADAL) for Python 轻松获取访问令牌。