Skip to content

Instantly share code, notes, and snippets.

@luis261
Last active April 3, 2024 14:25
Show Gist options
  • Save luis261/6c6f4c0a7d3bfa88272a7eeec682724d to your computer and use it in GitHub Desktop.
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 ..
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