6

With cURL, I can do --location-trusted to allow sending the name+password to all hosts the site may redirect to (http://curl.haxx.se/docs/manpage.html#--location-trusted).

Can I do something similar in Python with the requests library?

jianweichuah
  • 1,417
  • 1
  • 11
  • 22

3 Answers3

1

If you have to use libcurl (which you legitimately may!), you'll need to pass it the CURLOPT_UNRESTRICTED_AUTH option.

While the doc page itself doesn't mention it, this is the libcurl equivalent of the command line --location-trusted flag. See the CVE page where they introduced --location-trusted for more info.

s3cur3
  • 2,749
  • 2
  • 27
  • 42
0

requests will automatically take care of redirects: https://requests.readthedocs.io/en/latest/user/quickstart/#redirection-and-history
So, this should be a good place to start (if you haven't already gone through it): https://requests.readthedocs.io/en/latest/user/authentication/

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Adam
  • 561
  • 3
  • 8
0

You can use a urllib3.util.Retry object to tell requests to not remove the Authorization header when it has to retry a request because it was redirected.

import requests

from requests.adapters import HTTPAdapter, Retry

s = requests.Session()
# Default is {'Authorization'}
retries = Retry(remove_headers_on_redirect=set())
s.mount('http://', HTTPAdapter(max_retries=retries))

s.get("http://httpstat.us/301", auth=('user', 'password'))
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
  • I have no idea if this works, I just read [this github issue](https://github.com/urllib3/urllib3/issues/1316), this [SO question](https://stackoverflow.com/questions/23267409/how-to-implement-retry-mechanism-into-python-requests-library) and the docs I linked. – Boris Verkhovskiy Sep 06 '22 at 09:36