Can I preauthenticate with httplib2?

I need to perform preliminary basic authentication against an HTTP server, i.e. Authenticate immediately without waiting for a 401 response. Can this be done using httplib2?

Edit:

I solved this by adding an authorization header to the request, as suggested in the accepted answer:

 headers["Authorization"] = "Basic {0}".format(
        base64.b64encode("{0}:{1}".format(username, password)))
+5
source share
3 answers

Add the appropriate “Authorization” heading to your initial request.

+4
source

httplib ( , /). Jenkins, API, Jenkins .

>>> import base64, httplib
>>> headers = {}
>>> headers["Authorization"] = "Basic {0}".format(
        base64.b64encode("{0}:{1}".format('<username>', '<jenkins_API_token>')))

>>> ## Enable the job
>>> conn = httplib.HTTPConnection('jenkins.myserver.net')
>>> conn.request('POST', '/job/Foo-trunk/enable', None, headers)
>>> resp = conn.getresponse()
>>> resp.status
302

>>> ## Disable the job
>>> conn = httplib.HTTPConnection('jenkins.myserver.net')
>>> conn.request('POST', '/job/Foo-trunk/disable', None, headers)
>>> resp = conn.getresponse()
>>> resp.status
302
+4

, , , , Python 3 httplib2, . Jenkins, API Jenkins. Jenkins, Token API.

b64encode expects a binary string of ASCII characters. With Python 3, an Error type will be raised if a simple string is passed into it. To get around this, the "user: api_token" part of the header must be encoded using the "ascii" or "utf-8" passed to b64encode, then the resulting byte string must be decoded to a simple string before being placed in the header. The following code did what I needed:

import httplib2, base64

cred = base64.b64encode("{0}:{1}".format(
    <user>, <api_token>).encode('utf-8')).decode()
headers = {'Authorization': "Basic %s" % cred}
h = httplib2.Http('.cache')
response, content = h.request("http://my.jenkins.server/job/my_job/enable",
    "GET", headers=headers)
+1
source

All Articles