Python3: get resource from https server with client certificate authentication
-
20-12-2019 - |
Question
I have a problem getting html page from https server. Access to the resource is secured with client certificate verification (in a browser I must choose proper certificate to access page).
I am trying to use python's http.client
library like this:
import http.client
conn = http.client.HTTPSConnection('example.com', 443, key_file = 'tmp/private.pem', cert_file = 'tmp/public.pem')
conn.set_debuglevel(0)
conn.request('GET', '/index.htm')
result = conn.getresponse()
if result.status != http.client.ACCEPTED:
pass
print(result.status, result.reason)
conn.close()
As an output from this program I get: 403 Forbidden
. What am I doing wrong?
Note that I can access this resource directly through browser. The private and public keys are extracted from pkcs12 file exported from that browser with openssl commands (openssl pkcs12 -nocerts -nodes -in cert.p12 -out private.pem
and openssl pkcs12 -nokeys -in cert.p12 -out public.pem
)
Solution
Since I have not get any answer so far I would like to share with you what I have done and how I have resolved this issue.
I tried code sample that is in this StackOverflow question and slightly modify it to Python3:
from urllib.request import Request, urlopen, HTTPSHandler, build_opener
from urllib.error import URLError, HTTPError
import http.client
class HTTPSClientAuthHandler(HTTPSHandler):
def __init__(self, key, cert):
HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout=300):
return http.client.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
opener = build_opener(HTTPSClientAuthHandler(private_key_file, public_key_file))
response = opener.open("https://example.com/index.htm")
print response.read()
And it just has started to work. I still do not know how to resolve my original issue, but at least I know how to avoid it.
Hope that it will help!