Open In App

SSL Certificate Verification – Python requests

Requests verifies SSL certificates for HTTPS requests, just like a web browser. SSL Certificates are small data files that digitally bind a cryptographic key to an organization’s details. Often, a website with a SSL certificate is termed as secure website. By default, SSL verification is enabled, and Requests will throw a SSLError if it’s unable to verify the certificate.

Disable SSL certificate verification

Let us try to access a website with an invalid SSL certificate, using Python requests 






# import requests module
import requests
 
# Making a get request
response = requests.get('https://expired.badssl.com/')
 
# print request object
print(response)

Output :- 
 



This website doesn’t have SSL setup so it raises this error.
To disable certificate verification, at the client side, one can use verify attribute.  




# import requests module
import requests
 
# Making a get request
response = requests.get('https://expired.badssl.com/', verify = False)
 
# print request object
print(response)

Output 

Since output response 200 is printed, we can assume that request was successful.  

Manual SSL Verification

one can also pass the link to the certificate for validation via python requests only.  




# import requests module
import requests
 
# Making a get request
response = requests.get('https://github.com', verify ='/path / to / certfile')
 
# print request object
print(response)

This would work in case the path provided is correct for SSL certificate for github.com. 

Client Side Certificates

You can also specify a local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both files’ paths: 

>>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))

or persistent:  

s = requests.Session()
s.cert = '/path/client.cert'

If you specify a wrong path or an invalid cert, you’ll get a SSLError: 

>>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')
SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib

 


Article Tags :