I have got an API that I have to work with. The API is secured by HTTPS and uses mutual authentication/client certificates. I have a PEM file and a CRT file.
When I
I'm not sure - but it looks to me like you are missing doing the connect() call in the connect() method:
self.sock.connect(("someserver.com",443))
Also httplib
's https handling has wrapper classes for the SSL socket, so maybe those are required for it to work?
It looks like you're adding a lot of complexity here that you don't really need. If you're just doing simple client certificate authentication, you could probably get away from the following snippet (source):
import httplib
import urllib2
# HTTPS Client Auth solution for urllib2, inspired by
# http://bugs.python.org/issue3466
# and improved by David Norton of Three Pillar Software. In this
# implementation, we use properties passed in rather than static module
# fields.
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):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
cert_handler = HTTPSClientAuthHandler(settings.PEMFILE, settings.CLIENT_CERT_FILE)
opener = urllib2.build_opener(cert_handler)
urllib2.install_opener(opener)
f = urllib2.urlopen("https://sampleapiserver.com")
print f.code
The source was used in the context of providing a cert-authenicated URL opener to the Suds Client
constructor, so I stripped that out and made it a direct opener.