python 3 : get resource from https server with client certificate authentication

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

我在从 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 -在 cert.p12 -out public.pem)

最佳答案

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

我尝试了 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()

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

希望对您有所帮助!

关于 python 3 : get resource from https server with client certificate authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010067/

相关文章:

azure - 使用应用程序网关相互身份验证服务器变量在 APIM 上进行客户端证书验证

c# - 银光 TLS/SSL

javascript - $.ajax() 调用,仅在更新时

http - luaSocket HTTP 请求总是以重定向(301 或 302)响应

python - Flask 中具有可变数量路径参数的正斜杠

python - 你能简化 Python 中不等于或等于的链式比较吗?

c++ - 需要用于字符串和 HTTP 流的良好 C++ 库

google-chrome - 在 macOS Sierra 版本 10.12 上使用 Google Chrome 时,如何修复我的网站上的 NET::ERR_CERT_AUTHORITY_INVALID?

python - 为什么 Coverage.py 忽略没有覆盖的文件?

python - 如何在python3中精确打印大量小数对象?