[파이썬] requests SSL 인증서 검증

When making HTTP requests in Python, it is important to verify the SSL certificate of the server you are connecting to. This ensures secure and encrypted communication between your application and the server.

The popular requests library in Python makes it easy to perform HTTP requests. By default, requests verifies SSL certificates and throws an error if the certificate is invalid or expired. However, it is sometimes necessary to customize the SSL verification process.

Here, we will discuss how to perform SSL certificate verification with requests library in Python.

Disabling SSL Verification

In some cases, you may want to disable SSL certificate verification, for example, when working with self-signed certificates or when testing on a local development server without a valid certificate. While it is generally not recommended, you can disable SSL verification for a specific request by setting the verify parameter to False:

import requests

url = 'https://example.com'
response = requests.get(url, verify=False)

By passing verify=False, requests will not verify the SSL certificate and will accept any certificate presented by the server.

Customizing SSL Verification

To have more control over the SSL verification process, you can provide a custom certificate authority (CA) bundle. A CA bundle contains a list of trusted SSL certificates that requests will use to validate the server’s certificate.

import requests

url = 'https://example.com'
ca_bundle = '/path/to/ca_bundle.crt'
response = requests.get(url, verify=ca_bundle)

In the example above, the verify parameter is set to the path of the CA bundle file. This file contains the necessary SSL certificates to verify the server’s certificate.

Handling Invalid Certificates

If the server’s SSL certificate is invalid or expired, requests will raise a requests.exceptions.SSLError. To handle this gracefully, you can catch the exception and handle it accordingly.

import requests

url = 'https://example.com'
try:
    response = requests.get(url)
    # Process the response
except requests.exceptions.SSLError as e:
    # Handle the SSL error
    print(f"SSL certificate error: {str(e)}")

When an SSLError occurs, you can log the error, notify the user, or apply other error handling mechanisms based on your application’s requirements.

Conclusion

Verifying SSL certificates is crucial to ensure secure communication between your Python application and the server. The requests library makes it easy to perform SSL certificate verification with the ability to customize the process if needed.

By understanding how to disable SSL verification, provide a custom CA bundle, and handle SSL errors appropriately, you can effectively work with SSL certificates in your Python applications.