Custom urllib opener that uses client certificates

南笙酒味 提交于 2019-11-28 12:30:38

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!