Does urllib2 support pre-authentication?

I am trying to access the REST API.

I can get it to work in the Curl / REST client (user interface tool), with authentication enabled.

But, using urllib2, it apparently does not support this by default, and I cannot find a way to enable it.

Thank:)

+1
python urllib2
Jan 07 '11 at 17:52
source share
3 answers

It uses a simple Prefixive HTTP basic auth handler based on the code from urllib2.HTTPBasicAuthHandler . It can be used in exactly the same way, except that an Authorization header will be added to each request with a corresponding URL. Note that this handler must be used with HTTPPasswordMgrWithDefaultRealm . This is because there is no realm returning to the WWW-Authenticate task, since you are proactive.

 class PreemptiveBasicAuthHandler(urllib2.BaseHandler): def __init__(self, password_mgr=None): if password_mgr is None: password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() self.passwd = password_mgr self.add_password = self.passwd.add_password def http_request(self,req): uri = req.get_full_url() user, pw = self.passwd.find_user_password(None,uri) #logging.debug('ADDING REQUEST HEADER for uri (%s): %s:%s',uri,user,pw) if pw is None: return req raw = "%s:%s" % (user, pw) auth = 'Basic %s' % base64.b64encode(raw).strip() req.add_unredirected_header('Authorization', auth) return req 
+6
Dec 15 '11 at 1:11
source share

similar to @ thom-nichols answer; but the HTTPBasicAuthHandler subclass also handles HTTPS requests.

 import urllib2 import base64 class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler): '''Preemptive basic auth. Instead of waiting for a 403 to then retry with the credentials, send the credentials if the url is handled by the password manager. Note: please use realm=None when calling add_password.''' def http_request(self, req): url = req.get_full_url() realm = None # this is very similar to the code from retry_http_basic_auth() # but returns a request object. user, pw = self.passwd.find_user_password(realm, url) if pw: raw = "%s:%s" % (user, pw) auth = 'Basic %s' % base64.b64encode(raw).strip() req.add_unredirected_header(self.auth_header, auth) return req https_request = http_request 

here is an example of working with a jenkins server that does not send you 401 http errors (try again using auth). I use urllib2.install_opener to simplify the task.

 jenkins_url = "https://jenkins.example.com" username = "johndoe" api_token = "some-cryptic-value" auth_handler = PreemptiveBasicAuthHandler() auth_handler.add_password( realm=None, # default realm. uri=jenkins_url, user=username, passwd=api_token) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) 
+4
Jun 04 '14 at 22:38
source share

Depending on what type of authentication is required, you can send authorization headers manually by adding them to your request before sending the body.

0
Jan 07 '11 at 18:40
source share



All Articles