Kai Roesner
Kai Roesner

Reputation: 605

How to use a tempfile for certificate based authentication?

I want to fetch an OAuth token using client credentials with an X.509 certificate. I am using requests-oauthlib with the OAuth2 backend application flow. I'm getting the certificate and key at runtime from the framework I'm running in as strings not as file paths. Also I need to override the fetch_token() method of the library's OAuth2Session class to enable use of certificates because that's not yet available in the current 1.3.0 release.

The following works fine (with CertSession being my cert-enabled version of OAuth2Session):

from oauthlib.oauth2 import BackendApplicationClient
from .sessions import CertSession

# ... code to obtain client credentials (client_id, cert, key) from framework...

client = BackendApplicationClient(client_id=client_id)
session = CertSession(client=client)
token = None

with open('cert_file.pem', 'w') as cert_file:
    cert_file.write(cert)
    
with open('key_file.pem', 'w') as key_file:
    key_file.write(key)

try:
    token = session.fetch_token(token_url=token_url, include_client_id=True, cert=(cert_file.name, key_file.name))
    print(token)
except Exception as e:
    print(str(e))

However, I feel a bit uncomfortable with using plain old files for storing the certificate files. So I was trying to do the same using tempfile:

from oauthlib.oauth2 import BackendApplicationClient
from .sessions import CertSession
from tempfile import NamedTemporaryFile

# ... code to obtain client credentials (client_id, cert, key) from framework...

client = BackendApplicationClient(client_id=client_id)
session = CertSession(client=client)
token = None

cert_file = NamedTemporaryFile(mode='w', suffix='.pem')
cert_file.write(cert)
cert_file.flush()

key_file = NamedTemporaryFile(mode='w', suffix='.pem')
key_file.write(key)
key_file.flush()

try:
    token = session.fetch_token(token_url=token_url, include_client_id=True, cert=(cert_file.name, key_file.name))
    print(token)
except Exception as e:
    print(str(e))

which gives me ('Connection aborted.', PermissionError(13, 'Permission denied'))

What am I doing wrong?

Edit: It works with tempfiles if I open them with delete=False but that kinda defeats the purpose of using tempfiles in the first place, doesn't it?

Upvotes: 3

Views: 788

Answers (0)

Related Questions