我试图使用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请求的标题,以及如何使它工作?
使用请求库的2.4.3和Python2.7.9
发布于 2020-02-28 12:34:52
TLDR
您请求的url将POST请求重定向到另一个主机,因此请求库将删除Authoriztion头,以免泄露您的凭据。若要解决此问题,可以在请求的Session类中重写负责任的方法。
详细信息
在请求2.4.3中,reqeuests删除Authorization头的唯一位置是将请求重定向到另一个主机时。这是相关的代码
如果标题中的“授权”:#如果我们被重定向到一个新主机,我们应该去掉任何#身份验证头。original_parsed = urlparse(response.request.url) redirect_parsed = urlparse(url) if (original_parsed.hostname != redirect_parsed.hostname):del标头‘授权’
在较新版本的requests中,将在其他情况下删除Authorization报头(例如,如果重定向是从安全协议转到非安全协议的话)。
因此,在您的情况下可能发生的情况是,您的POST请求被重定向到另一个主机。使用请求库为重定向主机提供身份验证的唯一方法是通过.netrc文件。遗憾的是,这将只允许您使用,这对您没有多大帮助。在这种情况下,最好的解决方案可能是子类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-23 02:35:58
这就是请求文档中所写的:
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.
你的请求被重定向了吗?
如果是这种情况,请在post请求中禁用此选项的重定向:
allow_redirects=False
发布于 2020-02-28 15:43:58
我看到的第一个(也可能是实际的)问题是如何创建bearer_token,因为您不仅编码令牌,还编码身份验证类型'Bearer'。
正如我所理解的,您只需要对令牌进行编码,并且必须在请求头中提供空白身份验证类型+编码令牌:
bearer_token = str(base64.b64encode(access_token.encode()), "utf8")
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(bearer_token)}如果这也是一个重定向问题,您只需找出正确的位置并将请求发送到这个url,或者如果服务器正在接受此操作,则可以考虑在POST正文中发送访问令牌。
https://stackoverflow.com/questions/60358216
复制相似问题