Python 请求 : POST request dropping Authorization header

标签 python http python-requests http-headers authorization-header

我正在尝试使用 Python 请求库发出 API POST 请求。我正在通过 Authorization header ,但是当我尝试调试时,我可以看到 header 正在被删除。我不知道是怎么回事。

这是我的代码:

access_token = get_access_token()
bearer_token = base64.b64encode(bytes("'Bearer {}'".format(access_token)), 'utf-8')
headers = {'Content-Type': 'application/json', 'Authorization': bearer_token}
data = '{"FirstName" : "Jane", "LastName" : "Smith"}'
response = requests.post('https://myserver.com/endpoint', headers=headers, data=data)

如上所示,我手动设置了Authorization请求参数中的 header ,但缺少实际请求的 header :{'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.4.3 CPython/2.7.9 Linux/4.1.19-v7+'} .

另一条信息是,如果我将 POST 请求更改为 GET 请求,Authorization header 正常通过!

为什么这个库会删除 POST 请求的 header ,我该如何让它工作?

使用 requests lib 的 v2.4.3 和 Python 2.7.9

最佳答案

TLDR

您请求的 url 将 POST 请求重定向到不同的主机,因此请求库删除 Authoriztion标题,以免泄露您的凭据。要解决此问题,您可以覆盖请求中的负责方法 Session类(class)。

详情

在请求 2.4.3 中,reqeuests 的唯一位置删除 Authorization header 是当请求被重定向到不同的主机时。 This is the relevant code :

if 'Authorization' in headers:
    # If we get redirected to a new host, we should strip out any
    # authentication headers.
    original_parsed = urlparse(response.request.url)
    redirect_parsed = urlparse(url)

    if (original_parsed.hostname != redirect_parsed.hostname):
        del headers['Authorization']


requests 的较新版本中, Authorization在其他情况下将丢弃 header (例如,如果重定向是从安全协议(protocol)到非安全协议(protocol))。

因此,在您的情况下可能发生的情况是您的 POST 请求被重定向到不同的主机。使用 requests 库为重定向主机提供身份验证的唯一方法是通过 .netrc文件。遗憾的是,这只允许您使用 HTTP Basic Auth,这对您没有多大帮助。在这种情况下,最好的解决方案可能是子类 requests.Session并覆盖此行为,如下所示:
from requests import Session

class NoRebuildAuthSession(Session):
    def rebuild_auth(self, prepared_request, response):
        """
        No code here means requests will always preserve the Authorization
        header when redirected.
        Be careful not to leak your credentials to untrusted hosts!
        """

session = NoRebuildAuthSession()
response = session.post('https://myserver.com/endpoint', headers=headers, data=data)

编辑

我开了一个pull-request到 github 上的 requests 库以在发生这种情况时添加警告。它一直在等待第二次批准合并(已经三个月了)。

关于Python 请求 : POST request dropping Authorization header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358216/

相关文章:

python - asyncio start_server 超时问题

python - Tensorflow:在 CPU 中使用在 CUDNNLSTM 中训练的模型

python - 带有西里尔符号的 pytest 3.0.5

node.js - 调试 Electron/Node 应用程序时如何显示网络面板

javascript - node.js http 在浏览器中打开静态文本文件

python - 在 Python 请求中使用数据二进制

python - 使用 Python 请求的 SSL 客户端身份验证

python - 使用蓝图在 Flask 中设计 API

web-services - Web 服务器如何知道链接到它的是什么?

Python HDFS : Cannot read file