Search code examples
pythonsslaiohttp

aiohttp and certificate based authentication (cba)


I'm trying to use certificate based authentication (cba) with a cert file and key file to authenticate on a server. How can I achieve this with aiohttp? HTTP authentication with username and password works fine, but I couldn't find any example for cba.

I tried to expand the example from aiohttp documentation http://aiohttp.readthedocs.io/en/stable/client.html#ssl-control-for-tcp-sockets

async def main_ssl(loop):
    sslcontext = ssl.create_default_context()
    sslcontext.load_cert_chain(certfile=cert_file, keyfile=client_key)
    conn = aiohttp.TCPConnector(ssl_context=sslcontext)
    async with aiohttp.ClientSession(connector=conn) as session:
        await post_ssl(session)

But this gives me the following error:

aiohttp.errors.ClientOSError: [Errno 1] Cannot connect to host    
10.202.200.10:443 ssl:True [Can not connect to 10.202.200.10:443 [[SSL: 
CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)]]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f1dce7f5940>

Solution

  • You have to set the purpose of the context to CLIENT_AUTH (default=SERVER_AUTH).

    sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)