I'm trying to figure out how to specify an SSLContext with Request.
I have two functions which in theory should do the same, however the one with Requests doesn't work.
def func_OK(token):
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
ctx.load_cert_chain(certfile='myprivate.pem')
url = 'https://my_url.com'
hdr = {"Content-Type": "application/json","Authorization":"Bearer " token}
data = '{"filterList":[{}]}'
bdata = data.encode('utf-8')
req = urllib.request.Request(url, headers=hdr)
resp = urllib.request.urlopen(req, data=bdata, context=ctx)
content = resp.read()
data = json.loads(content.decode('utf-8'))
def func_NOK(token):
import requests
url = 'https://my_url.com'
hdr = {"Content-Type": "application/json","Authorization":"Bearer " token}
data = '{"filterList":[{}]}'
bdata = data.encode('utf-8')
resp = requests.post(url,headers=hdr, data={"filterList":[{}]})
The only the difference between the two functions are the sslContext. In the func_NOK, I try :
resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False)
- it doesn't workresp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem'))
- it doesn't workresp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt")
with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'
In any cases I have an SSL error. For example, on my last example the error msg is :
requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)
I'm just trying to use an SSLContext with Requests.
CodePudding user response:
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem') ctx.load_cert_chain(certfile='myprivate.pem')
load_cert_chain
loads the cert and private key for use as client certificate - which would be the cert
argument with requests
. cafile
describes the CA it should use to verify the server certificate - which would be the verify
argument for requests. Combined this would result in:
requests.post(..., cert='myprivate.pem', verify='myCA.crt.pem')
CodePudding user response:
I find where my cacert.pem : /home/<soome_path>/pyEnv/myEnv/lib/python3.8/site-packages/certifi/cacert.pem
I concatenated the files : myCA.crt.pem >> cacert.pem myprivate.pem>> cacert.pem
then I specified the path using verify : requests.post(...,verify='/home/<soome_path>/pyEnv/myEnv/lib/python3.8/site-packages/certifi/cacert.pem')
And I don't have the ssl error anymore. However I retrieve an html msg instead of a json. Maybe an issue on the parameters that I send to the endpoint.