📌  相关文章
📜  urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)> - Python (1)

📅  最后修改于: 2023-12-03 15:35:32.123000             🧑  作者: Mango

Python SSL certification verification error

Are you getting the following error message while performing an HTTPS request in Python?

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)> 

Don't worry, this error occurs due to an SSL certificate verification issue. When a client makes an HTTPS request, they generally use SSL/TLS to establish a secure connection with the server. During this process, SSL certificates (public key wrapped in a digital signature) are exchanged between the server and client to ensure that the server is authentic.

The SSL certificate chain typically consists of the server's SSL certificate and one or more intermediate certificates. An intermediate certificate authority (CA) signs and issues the server's SSL certificate. However, sometimes, the client's machine may not recognize or trust the intermediate certificate authority. This can result in the SSL verification failure error.

Solution

To solve this issue, you need to add the intermediate certificate authority to your client machine's trusted root store. Follow these steps:

  1. Open the Intermediate Certificate Authority's Certificate in your browser.

  2. Download the certificate in .pem format.

  3. Locate your machine’s trusted root store for SSL certificates. Generally, the store is located in /etc/ssl/certs/ca-certificates.crt.

  4. Append the content of the intermediate certificate file to the end of the trusted root store file.

  5. Save the changes, and you're done.

Do note that the intermediate certificate authority may differ based on the web server you're hitting. Therefore, you might need to repeat the above steps for every server you hit.

Alternatively, you can disable the SSL verification check by setting the verify parameter to False in your Python code. However, this isn't a recommended practice as it can leave your connection vulnerable to man-in-the-middle (MITM) attacks.

import ssl
import urllib.request

ssl._create_default_https_context = ssl._create_unverified_context

response = urllib.request.urlopen(url, context=ssl._create_unverified_context())

In the above code snippet, we're creating an SSL context with the ssl._create_unverified_context() method, which disables the SSL verification check. However, this method has security implications, which is why it's best to opt for the first method of adding the certificate to your trusted root store instead.

I hope this guide helped you understand the root cause of Python's SSL certificate verification error, and you were able to fix it using the provided solutions.