Python3:如何使用客户端证书认证从https服务器获取资源

3

我遇到了一个问题,无法从https服务器获取html页面。访问该资源需要进行客户端证书验证(在浏览器中,我必须选择正确的证书才能访问页面)。

我尝试使用Python的http.client库,代码如下:

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()

作为该程序的输出,我得到了:403 Forbidden。我做错了什么?
请注意,我可以直接通过浏览器访问此资源。私钥和公钥是从用openssl命令从导出的pkcs12文件中提取的(openssl pkcs12 -nocerts -nodes -in cert.p12 -out private.pemopenssl pkcs12 -nokeys -in cert.p12 -out public.pem)。
1个回答

0

由于我到目前为止还没有得到任何答案,所以我想与您分享我所做的和如何解决这个问题。

我尝试了这个StackOverflow问题中的代码示例,并稍微修改了它以适用于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()

而且它刚刚开始工作。 我仍然不知道如何解决我的原始问题,但至少我知道如何避免它。

希望这会有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接