【问题标题】:Python Requests Microsoft Graph API AuthenticationPython 请求 Microsoft Graph API 身份验证
【发布时间】:2018-12-02 06:10:03
【问题描述】:

我在使用 Python 为 Microsoft Graph API 接收不记名令牌时遇到问题。这是我目前所拥有的:

import requests
import json

headers = {
'Content-Type': 'x-www-form-urlencoded',
'Authorization': 'Basic'
}

data = {
"grant_type": "client_credentials",
"client_id" :"<client_id>",
"client_secret": "<client_secret>",
"resource": "https://graph.microsoft.com"
}

r = requests.post('<token_address>', headers=headers, data=data)
print(r.text)

我通过 x-www-form-urlencoded 在 Postman 中工作,但似乎无法在 Python 中工作。它返回请求正文必须包含以下参数:'grant_type'。我意识到问题可能与需要转换的数据有关,但我不确定从哪里开始。

【问题讨论】:

标签: python oauth-2.0 python-requests microsoft-graph-api


【解决方案1】:

您在请求中发送了一些无效的标头:

  • Content-Type 应该是 application/x-www-form-urlencoded 而不是 x-www-form-urlencoded
  • 您根本不应该发送Authorization 标头。

从技术上讲,由于 requests.post 默认以编码形式发送数据,因此您可以安全地从请求中删除您的 headers

payload = {
    'grant_type': 'client_credentials',
    'client_id': '<client_id>',
    'client_secret': '<client_secret>',
    'resource': 'https://graph.microsoft.com',
    }
r = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=payload)
print(r.text)

【讨论】:

    【解决方案2】:

    我相信 OAuth 期望正文是 URL 编码的,如下所示:

    data = "grant_type=client_credentials"
        + "&client_id=<client_id>"
        + "&client_secret=<client_secret>"
        + "&resource=https://graph.microsoft.com"
    

    【讨论】:

    • 不幸的是,它仍然返回相同的错误。
    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多