Using client certificates with urllib2

Ned Batchelder picture Ned Batchelder · Dec 9, 2009 · Viewed 18.5k times · Source

I need to create a secure channel between my server and a remote web service. I'll be using HTTPS with a client certificate. I'll also need to validate the certificate presented by the remote service.

  1. How can I use my own client certificate with urllib2?

  2. What will I need to do in my code to ensure that the remote certificate is correct?

Answer

tghw picture tghw · Dec 16, 2010

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, 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()