使用证书进行身份验证的 Python REST 请求

3

我尝试使用基于证书的身份验证向提供REST API的特定服务器发送Python中的REST请求,但是经过几个小时的搜索和尝试后,我认为我需要帮助。

我有来自所提到服务器的已签名证书和该证书的密钥。服务器本身也为https提供证书。

我尝试了httplib.HTTPSConnection库:

    import httplib
    import urllib
clientCert = "client.crt" clientKey = "client.key" serverCert = 'server.crt' serverApi = "/api/getExample" serverHost = "restapi.example.com" serverPort = 443 requestMethod = "POST" params = urllib.urlencode({'someId': 'myId'}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "application/json"}
conn = httplib.HTTPSConnection(serverHost, serverPort, key_file=clientKey, cert_file=clientCert) conn.request(requestMethod, serverApi, params, headers) response = conn.getresponse() conn.getresponse() conn.close()

我得到ssl.SSLError:SSL: CERTIFICATE_VERIFY_FAILED
使用该库可以实现基于证书的身份验证吗?

2个回答

9
我使用"requests"库成功运行了它。
import json
import requests
    
clientCrt = "cc.crt"
clientKey = "ck.key"
url = "https://example.com/api"
payload = { "someId": "myID" }
certServer = 'cs.crt'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), verify=certServer, 
                  headers=headers, cert=(clientCrt, clientKey))
print(r.status_code)
print(r.json())

就是这么简单

1
虚拟问题:在你的代码中,clientCrtclientKey是文件路径还是包含证书和密钥的字符串?如果是前者,那么如果我只有后者,该怎么办呢? - Kai Roesner
我也想知道。 - KevinLee
抱歉回复晚了 @KaiRoesner: 这是一个文件路径。更多信息可以查看这个链接: https://docs.python-requests.org/en/latest/user/advanced/ (在“客户端证书”主题下) - Carlo-Rodriguez

0
谢谢卡洛。
如果一个文件用于客户端证书,那么它必须包含完整的证书链、客户端证书和私钥,否则会出现“HTTPSConnectionPool(host='host, port=4443): Max retries exceeded with url: /api/endpoint (Caused by SSLError(SSLError(9, '[SSL] PEM lib (_ssl.c:3921)')))”错误。

1
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,以帮助他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined
1
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接