Search code examples
pythonpython-requestspyopenssl

Django Request with a SSL Certificate


Within a django view, I am required to make a post request to another API. The API requires SSL certificate to be attached to the request. I have the ssl .crt file.

How can I implement this?

I tried to use this implementation here: https://gist.github.com/erikbern/756b1d8df2d1487497d29b90e81f8068

But I would get this error even when I ran pycharm as administrator:

Traceback (most recent call last):
  File "C:\Applications\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Applications\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Applications\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "", line 350, in pge_auth_v1_redirect_view
    with pfx_to_pem(pem_file_path, '') as cert:
  File "c:\program files\python37\Lib\contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "", line 271, in pfx_to_pem
    f_pem = open(t_pem.name, 'wb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\fpier\\AppData\\Local\\Temp\\tmpg7i7qtun.pem'

Solution

  • The solution I found was to create a pem file by concatonating the public and private files.

            req = requests.post(
                url,
                params=params,
                headers=headers,
                auth=client_auth,
                verify=True,
                cert=self._pem_file_path
            )