Skip to content

Instantly share code, notes, and snippets.

@aiguofer
Created February 13, 2017 15:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aiguofer/1eb881ccf199d4aaa2097d87f93ace6a to your computer and use it in GitHub Desktop.
Save aiguofer/1eb881ccf199d4aaa2097d87f93ace6a to your computer and use it in GitHub Desktop.
Creating a Python requests session using a passphrase protected Client side Cert
import ssl
from requests.adapters import HTTPAdapter
CFG_FILE = '<path_to_cfg>'
secure_hosts = [
'https://<host>'
]
class SSLAdapter(HTTPAdapter):
def __init__(self, certfile, keyfile, password=None, *args, **kwargs):
self._certfile = certfile
self._keyfile = keyfile
self._password = password
return super(self.__class__, self).__init__(*args, **kwargs)
def init_poolmanager(self, *args, **kwargs):
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=self._certfile,
keyfile=self._keyfile,
password=self._password)
kwargs['ssl_context'] = context
return super(self.__class__, self).init_poolmanager(*args, **kwargs)
def get_session():
def get_config():
with open(CFG_FILE) as reader:
return json.load(reader)
session = requests.Session()
adapter = SSLAdapter(**get_config())
for host in secure_hosts:
session.mount(host, adapter)
session.verify = False
return session
@yoavweiss
Copy link

Can you comment on the license/copyright of this code? Can it be integrated into an Apache license project?

@psteinroe
Copy link

Hi, how does the cfg file look like?

@dezmaeth
Copy link

dezmaeth commented Aug 9, 2021

it's a json file, take a look at the args on the init method, "certfile", "keyfile" and "password"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment