使用RestSharp验证服务器证书并发送客户端证书

问题描述 投票:0回答:1

我正在编写示例 C# 代码来使用 RestSharp 实现 mTLS 身份验证。

这是我的代码

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

}

当我执行客户端时,出现以下错误。

“请求被中止:无法创建 SSL/TLS 安全通道”

但是,相同的请求正在通过 Postman 进行。

任何人都可以建议我在这里做错了什么吗?

ssl tls1.2 restsharp x509certificate2 mtls
1个回答
0
投票

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

您的证书不包含关联的私钥。您不能仅使用证书的公共部分进行基于证书的身份验证。包含公共证书和私钥的文件通常具有

.pfx
.p12
文件扩展名,并且通常需要密码来解密私钥。

如果您的文件同时包含 RFC 7468 格式(PEM 编码)的公共证书和私钥,您可能需要使用 X509Certificate.CreateFromPem 工厂方法。

© www.soinside.com 2019 - 2024. All rights reserved.