You may sometimes see an InsecureRequestWarning when making HTTPS requests in Python, telling you:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
This warning indicates that your Python code is making requests over HTTPS, but without validating the server's SSL certificate. This leaves the connection vulnerable to man-in-the-middle (MITM) attacks.
Let's discuss why you might be seeing this warning and how to properly validate certificates to fix it.
Why Does This Warning Occur?
By default, Python will trust any SSL certificate presented by a server when you make an HTTPS request. This is insecure because it allows the possibility of a bad actor intercepting the request and presenting their own fake certificate.
To prevent this, we need to explicitly enable certificate validation in requests so that Python will verify that the certificate is valid and trusted.
The
Enabling Certificate Validation
The easiest way to enable certificate validation is by passing the
import requests
url = "https://example.com"
response = requests.get(url, verify=True)
Setting
Alternatively, you can pass the path to a custom CA bundle file containing certificates:
response = requests.get(url, verify="path/to/ca/bundle.pem")
If you need more customization around certificate validation, you can pass an
import ssl
context = ssl.create_default_context(cafile="path/to/ca/bundle.pem")
response = requests.get(url, verify=context)
Troubleshooting Issues
Sometimes you may still run into
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
This typically means that the server is presenting a certificate that cannot validated against the root certificates.
There are a few potential causes:
Depending on the circumstances, you have a few options to resolve these problems:
Key Takeaways
Enabling SSL certificate verification helps protect your Python applications from attacks. Taking the time to properly handle certificates will give you more secure HTTPS connections.