Search code examples
asp.net-corepostmanswaggerasp.net-core-webapi

Why my ASP.NET Core app complains about invalid certificate?


My ASP.NET Core client app generates an error. When debugged, it fails on the HttpResponseMessage line

...
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);
...

I get this error:

SSL connection could not be established: AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch.

The token endpoint is correct, I don't get any response errors (401, 403..etc) to help me troubleshoot possible code related stuff.

If I run the test using Postman, it works fine.

Trying to understand the difference, the only thing I see is that Postman has "SSL configuration" off and "ca certificate" off (by default).

I even exported the cert from server (where the API is running) and import it to client were running the ASP.NET Core client app - no luck :(

So at this time my question is: why does Postman not complain about cert mismatch?


Solution

  • So at this time my question is: why does Postman not complain about cert mismatch?

    You are not getting error with postman because you have set the Postman to disable SSL certificate verification. that means Postman will ignore certificate errors, such as a mismatch between the certificate's hostname and the server's hostname.

    To resolve the error first you could check the server's certificate matches the expected hostname.

    Install the certificate in the trusted root folder of the machine certificate.

    • Open the Run dialog (Win + R), type mmc, and press Enter.
    • In the MMC window, go to File > Add/Remove Snap-in...
    • Select Certificates from the list of available snap-ins, and click
      Add.
    • Select Computer Account, and click Next.
    • Select Local Computer and click Finish, then click OK to close the
      Add/Remove Snap-in window.
    • Navigate to Certificates (Local Computer) > Trusted Root
      Certification Authorities > Certificates.
    • Right-click in the right pane, select All Tasks, and click Import.
    • Export the self-signed certificate in advance, and then follow the
      wizard to import the self-signed certificate.

    Or you could ignore this certificate error by using code:

    var handler = new HttpClientHandler
       {
           ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
       };
    
       using (var client = new HttpClient(handler))
       {
           var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
           HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);
           ...
           .......
       }