use python requests module to access asp.net core localhost pages with self signed https certificate

Viewed 199

This question mainly contains two parts:

  1. python requests as client, latest version (2.22.0)
  2. asp.net core 5.0 as server

There are lot of blogs, Q/A and docs online about each of them seperately concerning certificates, I've read a lot. but rarely together, and that's why I ask here.


Goal:
use python requests module to access asp.net core localhost pages with self signed https certificate.


Steps:

  1. Create a new .net5 emtpy website using VS, and run, it is hosted in "https://localhost:44355", shows pretty well in Chrome(showing string hello world), and I check the http certificate and export to exported.pem, whose content is like this:

-----BEGIN CERTIFICATE-----
MIIC7DCCAdSgAwIBAgIQEb7JqDAhyr5BxsGbq4Qp3TANBgkqhkiG9w0BAQsFADAU
... some lines of base64 strings
UvSjcGj1WTEEf8e6yPgqvyz6b6fQMpEyuu24SGtZt9A=
-----END CERTIFICATE-----

  1. Try python requests to get the page:
    import requests
    import certifi
    
    url = 'https://localhost:44355'
    requests.get(url, verify=False)  # working
    requests.get(url, verify='path to exported pem')  # not working
    print(certifi.where())
    #gets the distribution\lib\site-packages\certifi\cacert.pem

verify='path to exported pem' gets exception:

requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=44355): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

But if I create a .net 5 console application, without specifying certificate, will work:

        static void Main(string[] args)
        {
            HttpClient hc = new HttpClient();
            Console.WriteLine(hc.GetAsync("https://localhost:44355").Result.StatusCode);
            //prints OK
            Console.ReadKey();
        }

Investigations:

  • Tried various kinds of certificate formats, such pfx, der, etc.
  • Tried export from Chrome and Windows mmc, and seems are same things.
  • Tried openssl verify localhost.crt and got

CN = localhost error 20 at 0 depth lookup: unable to get local issuer certificate error localhost.crt: verification failed

  • Tried appending the exported pem contents to site-packages\certifi\cacert.pem file.

  • Some dotnet docs online talk about how to generate new certificate and use, or it may be automatically done when first time create new dotnet core project. I don't remember when I did that. So re-generating is not option, I just want to use the working one.

Any comments are welcome!

0 Answers
Related