I am trying access a REST API.
I can get it working in Curl/REST Client (the UI tool), with preemptive authentication enabled.
But, using urllib2, it doesn't seem to support this by default and I can't find a way to turn it on.
Thanks :)
I am trying access a REST API.
I can get it working in Curl/REST Client (the UI tool), with preemptive authentication enabled.
But, using urllib2, it doesn't seem to support this by default and I can't find a way to turn it on.
Thanks :)
Here's a simple Preemptive HTTP basic auth handler, based on the code from
urllib2.HTTPBasicAuthHandler
. It can be used in the exact same manner, except anAuthorization
header will be added to every request with a matching URL. Note that this handler should be used with aHTTPPasswordMgrWithDefaultRealm
. That's because there is no realm coming back in aWWW-Authenticate
challenge since you're being preemptive.similar to @thom-nichols's answer; but subclassing
HTTPBasicAuthHandler
also handling HTTPS requests.here is an example for dealing with a jenkins server which does not send you
401
http errors (retry with auth). I'm usingurllib2.install_opener
to make things easy.Depending on what kind of authentication is required, you can send the Authorization headers manually by adding them to your request before you send out a body.