简体   繁体   中英

How to authenticate SSL certificates using RestSharp c#

The location of the certificates

Inherit auth from parent

The test in postman

I want to use Restsharp to send this GET request -

This is what I want to send -

Request - GET,

URL - https://18.0.1.230:8080/api/report/test ,

Header - Key = Content-Type, Value = application/x-www-form-urlencoded

On Postman, I am not sending anything on Authorisation type (its set on "Inherit auth from parent") check 'inherit auth from parent' image

I have set Client certificates in Postman, so I have set the location of them, which postman uses when sending this request. Check 'Location of certificate' image

I want to know how do I add these certificates to a GET request using restSharp c# code, so that I pass the authentication and can get a 200 response?

What you need to do is first import the certificates:

public static async Task<X509Certificate2> LoadPemCertificate(string certificatePath, string privateKeyPath)
        {
            using var publicKey = new X509Certificate2(certificatePath);

            var privateKeyText = await File.ReadAllTextAsync(privateKeyPath);
            var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries);
            var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]);
            using var rsa = RSA.Create();

            if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY")
            {
                rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
            }
            else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY")
            {
                rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
            }

            var keyPair = publicKey.CopyWithPrivateKey(rsa);
            return new X509Certificate2(keyPair.Export(X509ContentType.Pfx));
        }

Once you're you have loaded the certificate in memory, all you have to do is attach certificate to restsharp client:

 var client = new RestClient("https://18.0.1.230:8080/api/report/test"); 
 client.ClientCertificates.Add(new X509Certificate(certificate));
...
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM