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

Share:
16,093
Carlo-Rodriguez
Author by

Carlo-Rodriguez

I am a software developer from germany who loves coding and stuff :)

Updated on June 04, 2022

Comments

  • Carlo-Rodriguez
    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
    Kai Roesner over 2 years
    Dummy question: In your code, are clientCrt and clientKey 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
    KevinLee almost 2 years
    I'd like to know that as well
  • Carlo-Rodriguez
    Carlo-Rodriguez almost 2 years
    sorry 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")