【问题标题】:Why does Bearer not work in requests authorization header?为什么 Bearer 在请求授权标头中不起作用?
【发布时间】:2023-04-10 02:23:01
【问题描述】:

我在通过 python 请求将带有 Bearer 的授权令牌发送到 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 工作(以及邮递员)并且 python 请求失败?

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

更新:

所以这段代码在 10 次中有 1 次有效(其他 9+ 给我 401 未经授权):

 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)

如果我在邮递员中按下提交,它每次都可以正常工作。

【问题讨论】:

  • c. 12e 似乎不是正确的标记。通常它们不包含空格。
  • 删除了它不在字符串中的空格 - 这不是真正的令牌。
  • 如果你使用'Authorization': 'Bearer c.123'而不是调用str函数,python版本是否工作?
  • @DavidWhitlock,不,我不是只是得到相同的 401 未经授权。也经过邮递员测试,效果很好。
  • 删除评论并添加到问题正文

标签: python authorization nest-api


【解决方案1】:

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

所以这里有一个处理这个问题的原型方法:

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)

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 2020-07-31
    • 2021-07-20
    • 2021-08-28
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2020-09-16
    相关资源
    最近更新 更多