Custom urllib opener that uses client certificates

后端 未结 2 1116
忘掉有多难
忘掉有多难 2020-12-11 05:52

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

相关标签:
2条回答
  • 2020-12-11 06:36

    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?

    0 讨论(0)
  • 2020-12-11 06:56

    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.

    0 讨论(0)
提交回复
热议问题