12

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

这是我的代码:

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在请求参数中手动设置了标头,但它缺少实际请求的标头: {'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标头会正常通过!

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

使用 requests lib 的 v2.4.3 和 Python 2.7.9

4

6 回答 6

20

TLDR

您请求的 url 会将 POST 请求重定向到不同的主机,因此请求库会丢弃Authoriztion标头,以免泄露您的凭据。要解决这个问题,您可以覆盖请求Session类中的负责方法。

细节

reqeuests在 requests 2.4.3 中,删除标头的唯一位置Authorization是当请求被重定向到不同的主机时。这是相关代码

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']

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

因此,在您的情况下可能发生的情况是您的 POST 请求被重定向到不同的主机。使用请求库为重定向主机提供身份验证的唯一方法是通过.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)

编辑

我已经向 github 上的请求库打开了一个拉取请求,以便在发生这种情况时添加警告。它一直在等待第二次批准合并(已经三个月了)。

于 2020-02-28T12:34:52.307 回答
2

这就是请求文档所说的:

Authorization headers set with headers= will be overridden if credentials are specified in .netrc, which in turn will be overridden by the auth= parameter. Authorization headers will be removed if you get redirected off-host.

您是否在请求中被重定向?

如果是这种情况,请尝试在发布请求中使用此选项禁用重定向:

allow_redirects=False

于 2020-02-23T02:35:58.237 回答
0

我看到的第一个(也许是实际的)问题是你是如何创建bearer_token的,因为你不仅要编码你的令牌,还要编码身份验证类型'Bearer'

据我了解,您只需要对令牌进行编码,并且必须在请求标头中提供空白身份验证类型 + 编码令牌:

bearer_token = str(base64.b64encode(access_token.encode()), "utf8")
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(bearer_token)}

如果它(也)是一个重定向问题,您可以简单地找出正确的位置并向这个 url 发出请求,或者POST如果服务器接受这个,您可能会考虑在您的正文中发送访问令牌。

于 2020-02-28T15:43:58.963 回答
0

从文档中:Requests will attempt to get the authentication credentials for the URL’s hostname from the user’s netrc file. The netrc file overrides raw HTTP authentication headers set with headers=. If credentials for the hostname are found, the request is sent with HTTP Basic Auth.

如果您被重定向,您可以尝试使用allow_redirects=false

于 2020-03-02T14:37:32.940 回答
-1

您可以尝试在标题中使用自定义授权。

定义一个自定义身份验证类:

class MyAuth(requests.auth.AuthBase):
def __init__(self, bearer_token):
    self.username = None
    self.bearer_token = bearer_token

def __call__(self, r):
    r.headers['Authorization'] = self.bearer_token
    return r

然后使用它来发送请求:

headers = {'Content-Type': 'application/json'}

data = '{"FirstName" : "Jane", "LastName" : "Smith"}'

response = requests.post('https://myserver.com/endpoint', headers=headers, auth=MyAuth(bearer_token), data=data)

如果这可行,请接受答案。或者,如果您仍有问题,请告诉我们。希望这可以帮助。

于 2020-02-25T12:18:03.677 回答
-1

使用“请求”库在 POST 请求中发送授权标头。在 Python 中只需使用这个:

requests.post('https://api.github.com/user', auth=('user', 'pass'))

这是一个基本的身份验证。

于 2020-06-17T10:59:03.987 回答