Using RestSharp to verify server certificate and send client certificate

50 views Asked by At

I'm writing a sample C# code to implement mTLS authentication with RestSharp.

Here is my code

using System;
using System.Net;
using RestSharp;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main(string[] args)
    {
            X509Certificate2 clientCertificate = new X509Certificate2(@"..\Certificate.crt"); 

            var client = new RestClient("https://apiurl:port"); 
            client.ClientCertificates = new X509CertificateCollection { clientCertificate };

            var request = new RestRequest("/testresource", Method.POST); 

            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;

            IRestResponse response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Request successful");
                Console.WriteLine("Response content: " + response.Content);
            }
            else
            {
                Console.WriteLine("Request failed with status code: " + response.StatusCode);
                Console.WriteLine("Error message: " + response.ErrorMessage);
            }
    }

private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        // No SSL policy errors, the certificate is considered valid
        return true;
    }

    // Check if any errors in the certificate chain
    if (chain == null || chain.ChainStatus == null)
    {
        // Certificate chain is not available or invalid
        return false;
    }

    // Check each chain status
    foreach (X509ChainStatus status in chain.ChainStatus)
    {
        if (status.Status != X509ChainStatusFlags.NoError)
        {
            // There is an error in the certificate chain, so it's considered invalid
            return false;
        }
    }


    // If we've reached here, the certificate chain is valid, but SSL policy errors are present
    // If you want to accept certificates with SSL policy errors, uncomment the line below
    //return true;

    // Otherwise, we consider the certificate invalid if SSL policy errors are present
    return false;
}

}

When I execute the client, I get the below error.

"The request was aborted: Could not create SSL/TLS secure channel"

However same request is working via Postman.

Can anyone suggest what could I be doing wrong here.

1

There are 1 answers

1
Crypt32 On

X509Certificate2 clientCertificate = new X509Certificate2(@"..\Certificate.crt");

your certificate doesn't contain associated private key. You cannot do certificate-base authentication using only public part of the certificate. Files that contain both, public certificate and private key often have .pfx or .p12 file extension and often require password to decrypt the private key.

If your file contains both, public certificate and private key in RFC 7468 format (PEM-encoded), you may need to use X509Certificate.CreateFromPem factory method.