【问题标题】:How to use certificate authentication in Simple.OData.Client?如何在 Simple.OData.Client 中使用证书身份验证?
【发布时间】:2017-03-10 02:14:34
【问题描述】:

如何在 Simple.OData.Client 中进行证书认证?我有 X509Certificate2 我想在调用 api 时使用它。我使用 .net 框架 4.6。

我做了一些搜索,我知道可以通过 HttpClientHandler 添加。但我无法弄清楚如何做到这一点。下面是我的代码。

void foo()
{
   var clientSettings = new ODataClientSettings("");
   clientSettings.OnApplyClientHandler = new Action<HttpClientHandler>(AddClientCertificate);
   var client = new ODataClient(clientSettings);
}

private void AddClientCertificate(HttpClientHandler handler )
{
// I have working code to retrieve the certificate.
X509Certificate2 targetCertificate = RetrieveCertificate();

//TODO : Add the certificate to the HttpClientHandler
}

【问题讨论】:

    标签: c# odata simple.odata simple.odata.client


    【解决方案1】:

    : 使用ODataClientSettings.OnCreateMessageHandler 并返回WebRequestHandler 并设置ClientCertificates

    I have found the solution from this github issue:

    再次查看代码后,您需要为 OnCreateMessageHandler 而不是 OnApplyClientHandler 分配一个委托,因为底层代码创建一个 HttpClientHandler 并且您需要一个 WebRequestHandler 例如

    var setting = new ODataClientSettings(baseAddresss, credentials) 
    {
         OnCreateMessageHandler = { 
         var handler = new WebRequestHandler();
         handler.ClientCertificates.Add(certificate);
    
         return handler;
         }
    }
    

    请注意,如果您这样做,它将不会调用 OnApplyClientHandler,因此您还必须在此委托中分配任何其他消息处理程序。 由于我无法访问受证书保护的站点,因此无法轻松检查此内容,但代码中没有任何内容表明这不起作用。

    【讨论】:

      【解决方案2】:

      希望下面的代码 sn-ps 之一工作正常!

      1. X509Certificate2 targetCertificate = RetrieveCertificate(); handler.ClientCertificates.Add(targetCertificate);

      2. var filePath = rootPath + @"/App_Data/apigee.pfx";
        X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.Import(filePath, "test", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
        httpClientHandler.ClientCertificates.AddRange(certificates);

      【讨论】:

        猜你喜欢
        • 2012-01-10
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2019-03-08
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        相关资源
        最近更新 更多