使用客户端证书的 Twisted http 客户端

Twisted http client using client certificate

我正在尝试编写一个扭曲的 https 客户端,它使用客户端证书进行身份验证。这是扭曲文档中用于发出简单 https 请求的示例:

from __future__ import print_function

from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

agent = Agent(reactor)

d = agent.request(
    b'GET',
    b'https://127.0.0.1:8880/test',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbResponse(ignored):
    print('Response received')
d.addCallback(cbResponse)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

我找到了 this 有关如何使用带有 ssl 证书的客户端的说明。不过,我不知道如何告诉代理使用证书进行身份验证。有什么想法吗?

IPolicyForHTTPS 构造 Agent 可以创建 contextFactory 来为 TLS 连接提供客户端证书。

certData = getModule(__name__).filePath.sibling('public.pem').getContent()
authData = getModule(__name__).filePath.sibling('server.pem').getContent()
clientCertificate = ssl.PrivateCertificate.loadPEM(authData)
authority = ssl.Certificate.loadPEM(certData)
options = ssl.optionsForClientTLS(u'example.com', authority,
                                  clientCertificate)

class SinglePolicy(object):
    def creatorForNetloc(self, hostname, port):
        return options

agent = Agent(reactor, SinglePolicy())