python certificate based authentication in REST request
16,093
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
Author by
Carlo-Rodriguez
I am a software developer from germany who loves coding and stuff :)
Updated on June 04, 2022Comments
-
Carlo-Rodriguez almost 2 years
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? -
Kai Roesner over 2 yearsDummy question: In your code, are
clientCrt
andclientKey
supposed to be file paths or strings containg the certificate and key themselves? If the former, how can I do that if I have only the latter? -
KevinLee almost 2 yearsI'd like to know that as well
-
Carlo-Rodriguez almost 2 yearssorry for the late response @KaiRoesner: its a file path. For more info you can check this: docs.python-requests.org/en/latest/user/advanced (under the topic "Client Side Certificates")