繁体   English   中英

如何解决[SSL: CERTIFICATE_VERIFY_FAILED] 在不绕过SSL 验证的情况下使用urllib 时出错

[英]How to Solve [SSL: CERTIFICATE_VERIFY_FAILED] Error when Using urllib without bypassing SSL verification

import urllib.request
import json
    
gojson = 'https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=17025436&class=highway&addressdetails=1&hierarchy=0&group_hierarchy=1&format=json&polygon_geojson=1'
res_body = urllib.request.urlopen(gojson).read()

错误:

URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)>

我知道我可以通过使用以下代码来解决错误:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

但我更想知道如何解决这个问题。 我在网上搜索时找不到解决方案。 有什么建议吗?

一种方法是将urllib.request.urlopen()可选的“ cafile ”参数与受信任的 CA 包的完整路径一起传递,例如由certifi生成的“cacert.pem”文件。 这可以通过certifi包中的certifi.where()来完成。

示例,使用您的代码片段:

import certifi  #added import
import json
import urllib.request


gojson = 'https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=17025436&class=highway&addressdetails=1&hierarchy=0&group_hierarchy=1&format=json&polygon_geojson=1'
res_body = urllib.request.urlopen(gojson, cafile=certifi.where()).read() #modified function call to add cafile argument

当然,你可以使用任何你想要的文件或路径,我只是提供了上面的例子,因为它需要在本地文件系统上进行较少的探索,并且对于最少的工作量来说似乎相对值得信赖。 使用经过验证的/受信任的 CA 包而不是关闭 ssl 验证通常是一种更安全的做法,这是一个很好的问题。

我的环境:macOS Big Sur,Python 3.9

参考:

  1. [提供 Mozilla 的 CA Bundle 的 Python 包。] https://pypi.org/project/certifi/
  2. [包仓库] https://github.com/certifi/python-certifi
  3. [功能详情] https://docs.python.org/3.9/library/urllib.request.html?highlight=urlopen#urllib.request.urlopen
  4. [证书颁发机构] https://www.ssl.com/faqs/what-is-a-certificate-authority/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM