当cURL工作时,Python请求库不工作

时间:2019-03-22 11:47:52

标签: python python-3.x python-requests jwt microsoft-graph

我需要使用Python从Microsoft API中检索JWT(JSON Web令牌)(请查看this Microsoft Graph的API文档)

以下使用requests库的Python代码无法提供HTTP响应代码400,但是,等效的cURL命令也可以有效地返回包含JWT的JSON。

Python / requests代码:

tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
    'Content-Type':  'application/x-www-form-urlencoded',
}
http_query_params = {
    "client_id": "<MY_FOO_C_ID>",
    "scope": "<MY_FOO_SCOPE>",
    "client_secret": "<MY_FOO_C_SECRET>",
    "grant_type": "client_credentials",
}
http_response = requests.post(token_url, params=http_query_params, headers=http_headers)

cURL命令:

curl -v -X POST \
  --data-urlencode 'client_id=<MY_FOO_C_ID>' \
  --data-urlencode 'scope=<MY_FOO_SCOPE>' \
  --data-urlencode 'client_secret=<MY_FOO_C_SECRET>' \
  --data-urlencode 'grant_type=client_credentials' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  'https://login.microsoftonline.com/<MY_FOO_TENANT>/oauth2/v2.0/token'

requests库的详细输出中,我可以看到它是对所有这些HTTP查询参数进行URL编码的,所以我倾向于认为这不是问题。

  • Python实现有什么问题?
  • 如何使其工作?

1 个答案:

答案 0 :(得分:2)

您应将http_query_params作为data而不是params传递。尝试以下代码:

tenant = "<MY_FOO_TENANT>"
token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant)
http_headers = {
    'Content-Type':  'application/x-www-form-urlencoded',
}
http_body = {
    "client_id": "<MY_FOO_C_ID>",
    "scope": "<MY_FOO_SCOPE>",
    "client_secret": "<MY_FOO_C_SECRET>",
    "grant_type": "client_credentials",
}
http_response = requests.post(token_url, data=http_body, headers=http_headers)

希望这会有所帮助