我想使用带有 X.509 证书的客户端凭据来获取 OAuth 令牌。我将requests-oauthlib与OAuth2 后端应用程序流一起使用。我在运行时从作为字符串而不是文件路径运行的框架中获取证书和密钥。此外,我需要重写fetch_token()
库OAuth2Session
类的方法以启用证书的使用,因为在当前的 1.3.0 版本中尚不可用。
以下工作正常(CertSession
作为我的启用证书的版本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))
但是,我对使用普通的旧文件来存储证书文件感到有点不舒服。所以我试图使用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))
这给了我
('Connection aborted.', PermissionError(13, 'Permission denied'))
我究竟做错了什么?
编辑:如果我打开它们,它可以与临时文件一起使用,delete=False
但这有点违背了首先使用临时文件的目的,不是吗?