Search code examples
python-requestspkcs#12p12

Should I use a session with p12-certificate


So I've writren a scraper that uses the requests_pkcs12-library and a .p12-cert.

Currently I'm making a lot a requests where I use it as described in the docs

from requests_pkcs12 import get

r = get('https://example.com/test', pkcs12_filename='clientcert.p12', pkcs12_password='correcthorsebatterystaple') 

The docs also show that you can use it in a session instead.

from requests import Session 
from requests_pkcs12 import Pkcs12Adapter 

session = Session()
session.mount('https://example.com', Pkcs12Adapter(pkcs12_filename='clientcert.p12', pkcs12_password='correcthorsebatterystaple')) 
r = session.get('https://example.com/test')

So this works fine as well. But what are the advantages of doing so? Does it put less presure on the server which it authenticates with?

It does not seem to be adding an authenticated cookie to the session so I was wondering why the one would be prefered over the other.

Does anyone know this?

Thanks in advance


Solution

  • Yes, using a session may improve performance on client-side and reduce the server-side load as well.

    Note that this has almost nothing to do with the requests_pkcs12 library, but is a generic mechanism of the requests library.

    The requests manual states:

    The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

    The linked Wikipedia entry for HTTP persistent connection states:

    Advantages

    • ...
    • Reduced CPU usage and round-trips because of fewer new connections and TLS handshakes.

    And the Wikipedia section on TLS handshakes states:

    Client-authenticated TLS handshake

    ...

    1. Negotiation Phase:
      • ...
      • The server sends a CertificateRequest message, to request a certificate from the client so that the connection can be mutually authenticated.
      • ...
      • The client responds with a Certificate message, which contains the client's certificate.

    To summarize, using a requests session leads to connection pooling which leads to fewer TCP connections and hence fewer TLS handshakes, which in turn means fewer client certificate authentications. Note that this is independent on how the client certificate was made available to requests, whether in PKCS12 format (using requests_pkcs12) or PEM format (using plain requests).