Categories
Posts

HTTP Basic Auth with httplib2

While working on pressfs I ran into an issue with httplib2 using HTTP Basic Authentication.

Here is some example code:

[sourcecode lang=”python”]
import httplib2

if __name__ == ‘__main__’ :
httplib2.debuglevel = 1

h = httplib2.Http()
h.add_credentials( ‘username’, ‘password’ )

resp, content = h.request( ‘http://www.google.com/’, ‘GET’ )
[/sourcecode]

If you run this you’ll notice that httplib2 doesn’t actually include the HTTP Basic Auth details in the request, even though the code specifically asks it to do so. By design it will always make one request with no authentication details and then check to see if it gets an HTTP 401 Unauthorized response back. If and only if it gets a 401 response back will it then make a second request that includes the authentication data.

Bottom line, I didn’t want to make two HTTP requests when only one was needed (huge performance hit). There is no option to force the authentication header to be sent on the first request, so you have to do it manually:

[sourcecode lang=”python”]
import base64
import httplib2

if __name__ == ‘__main__’ :
httplib2.debuglevel = 1

h = httplib2.Http()
auth = base64.encodestring( ‘username’ + ‘:’ + ‘password’ )

resp, content = h.request(
‘http://www.google.com/’,
‘GET’,
headers = { ‘Authorization’ : ‘Basic ‘ + auth }
)
[/sourcecode]

Watching the output of this you’ll see the authentication header in the request.

Someone else already opened an issue about this ( Issue 130 ), unfortunately Joe Gregorio has indicated that he has no intention of ever fixing this 🙁

On the up side, working around this deficiency only takes a little bit of extra code.