簡體   English   中英

為什么Bearer在請求授權標頭中不起作用?

[英]Why does Bearer not work in requests authorization header?

我在通過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請求失敗?

下圖顯示了郵遞員的相同工作:

在此處輸入圖片說明 更新:

因此,此代碼每10遍工作一次(另外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)

如果我在郵遞員中按“提交”,則每次都能正常運行。

導致這是Nest的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM