【问题标题】:Python3: get resource from https server with client certificate authenticationPython3:通过客户端证书身份验证从 https 服务器获取资源
【发布时间】:2014-08-13 05:22:09
【问题描述】:

我在从 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 命令(openssl pkcs12 -nocerts -nodes -in cert.p12 -out private.pemopenssl pkcs12 -nokeys -in cert.p12 -out public.pem)从该浏览器导出的 pkcs12 文件中提取的

【问题讨论】:

    标签: python http ssl python-3.x client-certificates


    【解决方案1】:

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

    我尝试了this StackOverflow question 中的代码示例,并将其稍微修改为 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()
    

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

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多