Using client certificates with urllib2 Using client certificates with urllib2 python python

Using client certificates with urllib2


Because alex's answer is a link, and the code on that page is poorly formatted, I'm just going to put this here for posterity:

import urllib2, httplibclass 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()


Per Antoine Pitrou's response to the issue linked in Hank Gay's answer, this can be simplified somewhat (as of 2011) by using the included ssl library:

import sslimport urllib.requestcontext = ssl.create_default_context()context.load_cert_chain('/path/to/file.pem', '/path/to/file.key')opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))response = opener.open('https://example.org')print(response.read())

(Python 3 code, but the ssl library is also available in Python 2).

The load_cert_chain function also accepts an optional password parameter, allowing the private key to be encrypted.