Last active
April 3, 2024 14:25
-
-
Save luis261/6c6f4c0a7d3bfa88272a7eeec682724d to your computer and use it in GitHub Desktop.
this can be quite handy when wanting to prevent unwarranted stripping of auth headers while staying "safe" via a fallback on super().rebuild_auth for redirects to entirely different hosts. Only use as a last resort; ideally opting for direct configuration of the host targeted by the redirects instead. If that is not feasible though, here you go ..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import warnings | |
class AuthPreservingSession(requests.Session): | |
trusted_host = requests.utils.urlparse("https://your.api.could.go.here").hostname | |
def rebuild_auth(self, prepared_request, response): | |
target_host = requests.utils.urlparse(prepared_request.url).hostname | |
if target_host is None or not target_host.endswith(self.trusted_host): | |
return super().rebuild_auth(prepared_request, response) | |
warnings.warn("Sustaining auth headers for redirect to: \"" + target_host + "\"") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment