I tried to send a REST request in python with a certificate based authentication to a given server that is providing the REST api's but after hours of searching and trying I think I need help.
I have a signed certificate from the mentioned server and the key for that cert. The Server itselfs does also provide a certificate for https.
I tried the library 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()
I get ssl.SSLError: SSL: CERTIFICATE_VERIFY_FAILED
Is it possible to get a cert based auth running with that library?
I was able to get it running with the aid of the "requests" library.
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())
Simple as that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With