Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using client certificates with urllib2

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?

like image 986
Ned Batchelder Avatar asked Dec 09 '09 16:12

Ned Batchelder


1 Answers

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()
like image 185
tghw Avatar answered Oct 04 '22 17:10

tghw