python - Python OAuth 客户端凭据授予类型返回 400,[错误:不支持的授予]类型,但 Curl 工作正常
问题描述
我对 API 非常陌生(仍在学习),requests
在尝试使用Client Credentials Grant Type启动 OAuth 身份验证流程时遇到了一个非常奇怪的 Python 库问题。
出于某种原因,每当我使用我的 Python 脚本(在requests
库的帮助下)将 HTTP 请求发送到身份验证端点时,我总是得到
Response Status Code: 400
Response Body/Data returned: {"error":"unsupported_grant_type"}
但是,如果我尝试使用curl
命令行工具发送请求,我将获得状态码为 200 的成功响应,响应正文中的访问令牌如下所示:
{'access_token': 'some access token',
'expires_in': 'num_of_seconds',
'token_type': 'Bearer'}
事实上,如果我尝试在我的 Python 脚本(带函数)中使用 Curl 命令行工具发送请求subprocess.Popen
,我可以获得状态码 200 和访问令牌没有问题的响应。
现在,话虽如此,这是我用来发送请求以启动 OAuth 身份验证流程的 Python 脚本:
import requests
import os
import base64
clientCredentialEndpoint = "https://base_url/path/token"
client_id = os.environ.get('CLIENT_ID')
client_secret = os.environ.get('CLIENT_SECRET')
# -- Encode the <client_id:client_secret> string to base64 --
auth_value = f'{client_id}:{client_secret}'
auth_value_bytes = auth_value.encode('ascii')
auth_value_b64 = base64.b64encode(auth_value_bytes).decode('ascii')
queryParams ={
'grant_type':'client_credentials',
'scope':'get_listings_data'
}
headers = {
'Authorization':f'Basic {auth_value_b64}',
'Content-Type':'application/x-www-form-urlencoded'
}
# send the post request to Authorisation server
response = requests.post(
clientCredentialEndpoint,
params=queryParams,
headers=headers,
)
print(response.status_code)
print(response.text)
而我使用(和工作)发送请求的 curl 命令是:
curl -X POST -u '<client_id>:<client_secret>' \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'grant_type=client_credentials&scope=get_listings_data' \
'https://base_url/path/token'
同样,就像我说的,如果我在 Python 脚本中执行此 curl 命令,它将成功返回访问令牌而没有问题。
有谁知道我在 Python 脚本中做错了什么导致我的请求总是失败?
提前致谢!
解决方案
天哪,我刚刚意识到-d
curl 命令中的 与查询参数不对应,它代表'data'。
因此,我只需要稍微更改一下我的 Python 脚本requests.post()
,使其看起来像这样:
response = requests.post(
clientCredentialEndpoint,
data=queryParams,
headers=headers,
)
希望这对其他人有帮助。
推荐阅读
- javascript - 如何使用 JavaScript 搜索包含所有列的表格
- html - 出现“错误 TS2339:“对象”类型上不存在属性“用户”的错误。”
- c# - 如何通过服务帐户在 c# 上使用 Admob API?
- java - 我的一个属性似乎无法识别 spring-boot-starter-actuator
- excel - Laravel Excel 插件思路
- python - 使用主管启动我的 Flask 应用程序
- ajax - 我试图做一个 QUnit 异步测试来检查 ajax 更新
- wordpress - 如何在 wordpress 中将帖子的图像显示为媒体库
- javascript - cefsharp ChromiumWebBrowser,我如何将 json 对象返回到 javascript,而不是字符串
- json - Jackson ObjectMapper 没有将 JSON 读取到 POJO