[英]Python Requests - Azure RM API returning 200 status code but 400 in content
I have some code where I am trying to authenticate against Azure's Resource Manager REST API. 我有一些代码要在其中尝试针对Azure的Resource Manager 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
This returns: 返回:
200
OK
However, when I print auth_response.content or auth_reponse.text, I get back a 400 HTML error code and an error message. 但是,当我打印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.
I am able to get back the correct information using PostMan, however, with the same URI and payload. 但是,我可以使用PostMan使用相同的URI和有效负载来获取正确的信息。 I used the "Generate Code" option in Postman to export my request to a Python requests script and tried running that. 我使用Postman中的“生成代码”选项将我的请求导出到Python请求脚本,并尝试运行该脚本。 But, I get the same errors. 但是,我得到同样的错误。
Anybody have any idea why this is happening? 有人知道为什么会这样吗?
You should use HTTPS instead of HTTP for token_endpoint, and you should specify API version too. 对于token_endpoint,应使用HTTPS而不是HTTP,并且还应指定API版本。 Here is what you should use. 这是您应该使用的。
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id
Only modify your token_endpoint
to https
Protocols. 仅将您的token_endpoint
修改为https
协议。 EG: token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id
. EG: token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id
。 You can refer to https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx for more details. 您可以参考https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx了解更多详细信息。
Meanwhile, you can leverage Microsoft Azure Active Directory Authentication Library (ADAL) for Python for acquire the access token in a ease. 同时,您可以利用适用于Python的Microsoft Azure Active Directory身份验证库(ADAL)轻松获取访问令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.