【问题标题】:How to authenticate SSL certificates using RestSharp c#如何使用 RestSharp c# 验证 SSL 证书
【发布时间】:2020-08-29 19:46:34
【问题描述】:

The location of the certificates

Inherit auth from parent

The test in postman

我想使用 Restsharp 发送这个 GET 请求 -

这是我要发送的 -

请求 - GET,

网址 - https://18.0.1.230:8080/api/report/test,

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

在 Postman 上,我没有发送任何关于授权类型的内容(其设置为“从父级继承身份验证”)检查“从父级继承身份验证”图像

我在 Postman 中设置了客户端证书,因此我设置了它们的位置,邮递员在发送此请求时使用该证书。检查“证书位置”图片

我想知道如何使用 restSharp c# 代码将这些证书添加到 GET 请求中,以便通过身份验证并获得 200 响应?

【问题讨论】:

    标签: c# automated-tests ssl-certificate postman restsharp


    【解决方案1】:

    你需要做的是首先导入证书:

    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));
            }
    

    一旦你将证书加载到内存中,你所要做的就是将证书附加到restsharp客户端:

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

    【讨论】:

    • 感谢您的回答.. 我使用了这篇文章中提供的解决方案 - stackoverflow.com/questions/49069197/…
    • 是的,首先转换为 pfx 是很常见的。上面的解决方案做同样的事情,但在代码中。
    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 2019-06-14
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多