Python请求:POST请求删除了Authorization标头

时间:2020-02-23 00:49:02

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

我正在尝试使用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请求的标头,我该如何使用它?

使用v2.4.3的请求lib和Python 2.7.9

6 个答案:

答案 0 :(得分:12)

TLDR

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

详细信息

在请求2.4.3中,reqeuests删除Authorization标头的唯一位置是将请求重定向到其他主机时。 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标头将被丢弃。

因此,在您的情况下可能会发生的情况是将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上的请求库中打开了pull-request,以在发生这种情况时添加警告。它一直在等待第二次批准合并(已经三个月了)。

答案 1 :(得分:0)

这是请求文档所说的:

.prop()

您是否在请求中得到重定向?

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

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.

答案 2 :(得分: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正文中发送访问令牌接受这个。

答案 3 :(得分: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

答案 4 :(得分:0)

使用“ request”库在POST请求中发送Authorization标头。在Python中 只需使用此:

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

这是基本的身份验证。

答案 5 :(得分:-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)

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