我有一些代码正在尝试针对 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
这将返回:
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 中的“生成代码”选项将我的请求导出到 Python 请求脚本并尝试运行该脚本。但是,我遇到了同样的错误。
有人知道为什么会发生这种情况吗?
最佳答案
仅将您的 token_endpoint
修改为 https
协议(protocol)。例如:
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用于轻松获取访问 token 。
关于Python 请求 - Azure RM API 返回 200 状态代码,但返回 400 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36437213/