gpt4 book ai didi

python - 为什么 Bearer 在请求授权 header 中不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:45 27 4
gpt4 key购买 nike

我在通过 python 请求将带有 Bearer 的授权 token 发送到 NEST API 时遇到问题:

curl https://developer-api.nest.com -H "Authorization: Bearer c.123"
-H "Content-Type: application/json"

工作正常,但是:

nest_url = "https://developer-api.nest.com"
headers = {'Authorization': str('Bearer ' + token), 'Content-type': 'application/json'}
print(headers)
nest_data_req = requests.get(nest_url, headers=headers)

打印为:

{'Content-type': 'application/json', 'Authorization': 'Bearer c.123'}

因 401 未授权而失败,据我所知,他们正在尝试发出相同的请求,那么为什么 curl 工作(以及 postman 就此而言)并且 python 请求失败?

下图显示了 postman 中的相同工作:

enter image description here更新:

所以此代码在 10 次中有效 1 次(其他 9 次以上给我 401 unauthorized):

 url = "https://developer-api.nest.com/"
auth_t = token.encode("ascii", "ignore")
headers = {
'authorization': "Bearer " + auth_t,
'content-type': "application/json",
'cache-control': "no-cache",
}
response = requests.request("GET", url, headers=headers)
print(response.text)

如果我在 postman 中按提交,它每次都能正常工作。

最佳答案

原来这是 nest 的 API 重定向的结果,因此您可以认为这是一个错误 - 因为 header 已从重定向的请求中删除,并且 header 应该在 session 中。或者他们试图解决 CVE 时的“功能”。

所以这是处理这个问题的原型(prototype)方法:

def get_nest_data(token):
url = "https://developer-api.nest.com/"
auth_t = token.encode("ascii", "ignore")
headers = {
'authorization': "Bearer " + auth_t,
'content-type': "application/json",
}

try:
init_res = requests.get('https://developer-api.nest.com', headers=headers, allow_redirects=False)
if init_res.status_code == 307:
api_response = requests.get(init_res.headers['Location'], headers=headers, allow_redirects=False)
if api_response.status_code == 200:
return api_response.json()
elif init_res.status_code == 200:
return init_res.json()
except Exception as ce:
print(ce)

关于python - 为什么 Bearer 在请求授权 header 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631500/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com