【问题标题】:Python Requests - Azure RM API returning 200 status code but 400 in contentPython 请求 - Azure RM API 返回 200 状态代码但内容为 400
【发布时间】:2016-04-05 21:17:09
【问题描述】:

我有一些代码尝试针对 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 请求脚本并尝试运行它。但是,我得到了同样的错误。

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

【问题讨论】:

    标签: python python-2.7 azure python-requests azure-resource-manager


    【解决方案1】:

    仅将您的 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 轻松获取访问令牌。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-11
        • 2015-12-08
        • 2022-12-02
        • 1970-01-01
        • 1970-01-01
        • 2020-07-18
        • 2020-09-02
        • 1970-01-01
        相关资源
        最近更新 更多