Friday, June 22, 2012

Python: HTTP Basic authentication with httplib

You can check how http basic authentication can be requested by the server from the user using php in this post.

To make an HTTP request that needs HTTP basic authentication you need to base64 encode the username and password like : base64encode(username + ':' + password) and add it to an HTTP header:

import base64
import string
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
webservice.putheader("Authorization", "Basic %s" % auth)

Example usage with httplib:
import httplib
import base64
import string

host = "host.or.ip"
url = "/url"
username = 'user'
password = 'pass'
message = 'some message'

# base64 encode the username and password
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

webservice = httplib.HTTP(host)
# write your headers
webservice.putrequest("POST", url)
webservice.putheader("Host", host)
webservice.putheader("User-Agent", "Python http auth")
webservice.putheader("Content-type", "text/html; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(message))
# write the Authorization header like: 'Basic base64encode(username + ':' + password)
webservice.putheader("Authorization", "Basic %s" % auth)

# get the response
statuscode, statusmessage, header = webservice.getreply()
print "Response: ", statuscode, statusmessage
print "Headers: ", header
res = webservice.getfile().read()
print 'Content: ', res


Roger said...

base64.encodestring() split the encoded string of my long username and password into multiple lines. base64.standard_b64encode() worked for me.

Unknown said...

Thank you for posting this!

Would you consider a similar post using Python 3.x? It could be very helpful for those of us who are exploring the 3.x world.