简体   繁体   中英

Can I do preemptive authentication with httplib2?

I need to perform preemptive basic authentication against an HTTP server, ie, authenticate right away without waiting on a 401 response. Can this be done with httplib2?

Edit:

I solved it 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)))

Add an appropriately formed 'Authorization' header to your initial request.

This also works with the built-in httplib (for anyone wishing to minimize 3rd-party libs/modules). I am using it to authenticate with our Jenkins server using the API Token that Jenkins can create for each user.

>>> 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

I realize this is old, but I figured I'd throw in the solution if you're using Python 3 with httplib2 since I haven't been able to find it anywhere else. I'm also authenticating against a Jenkins server using the API Token for each Jenkins user. If you're not concerned with Jenkins, simply substitute the actual user's password for the API Token.

b64encode is expecting an binary string of ASCII characters. With Python 3 a TypeError will be raised if a plain string is passed in. To get around this, the "user:api_token" portion of the header must be encoded using either 'ascii' or 'utf-8', passed to b64encode, then the resulting byte string must be decoded to a plain 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM