EDIT: 我已经提交了PR https://github.com/aio-libs/aiohttp/pull/1849更新了有关该主题的 aiohttp 文档,并且它已被合并。
对于将来可能遇到此问题的任何人..
TL:DR
import ssl
import aiohttp
ssl_ctx = ssl.create_default_context(cafile='/path_to_client_root_ca')
ssl_ctx.load_cert_chain('/path_to_client_public_key.pem', '/path_to_client_private_key.pem')
conn = aiohttp.TCPConnector(ssl_context=ssl_ctx)
session = aiohttp.ClientSession(connector=conn)
# session will now send client certificates..
长话短说 - 我已经了解了它是如何在请求中实现的(它整齐地记录了 APIhere http://docs.python-requests.org/en/master/user/advanced/#client-side-certificates),显然它是在内部实现的urllib3.
urllib3 滴下来cert
参数一直到其HTTPS连接 https://github.com/shazow/urllib3/blob/master/urllib3/connection.py#L208对象,最终调用此函数:
...
self.sock = ssl_wrap_socket(
sock=conn,
keyfile=self.key_file,
certfile=self.cert_file,
ssl_context=self.ssl_context,
)
...
它的作用是:
...
if ca_certs or ca_cert_dir:
try:
context.load_verify_locations(ca_certs, ca_cert_dir)
except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2
raise SSLError(e)
# Py33 raises FileNotFoundError which subclasses OSError
# These are not equivalent unless we check the errno attribute
except OSError as e: # Platform-specific: Python 3.3 and beyond
if e.errno == errno.ENOENT:
raise SSLError(e)
raise
elif getattr(context, 'load_default_certs', None) is not None:
# try to load OS default certs; works well on Windows (require Python3.4+)
context.load_default_certs()
if certfile:
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
...
这里有趣的调用是load_cert_chain
- 这意味着如果我们创建一个ssl.SSLContext
(这是一个标准库接口)对象和调用load_cert_chain
使用这样的客户端证书,aiohttp 的行为将与 requests\urllib3 相同。
因此,尽管 aiohttp 的文档没有告诉你这一点,但他们确实指定你可以加载自己的ssl.SSLContext
.