Friday, April 17, 2009

Client certificates with urllib2

First let's get pem formatted file with certificate and key from your *.pkcs12 or *.pfx file with openssl.
openssl pkcs12 -in file.p12 -out file.pem -nodes


Now we need to extend standart HTTPSHandler( I found it here. I added timeout to getConnection method. ) and sent instance of it to urllib2's build_opener.
import urllib2, httplib
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
#Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout=300):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

opener = urllib2.build_opener(HTTPSClientAuthHandler('/path/to/file.pem', '/path/to/file.pem.') )
response = opener.open("https://example.org")

print response.read()