4

How to do certificate authentication in Simple.OData.Client? I have X509Certificate2 which i want to use while calling the api. I use .net framework 4.6.

I did some search and I came to know it is possible to add through HttpClientHandler. But I'm not able to figure out how to do that. Below is the code i have.

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
}
shanmuga raja
  • 685
  • 6
  • 19

2 Answers2

0

Short: Use the ODataClientSettings.OnCreateMessageHandler and return a WebRequestHandler and setting the ClientCertificates.

I have found the solution from this github issue:

Having looked at the code again what you need to do is assign a delegate to OnCreateMessageHandler rather than OnApplyClientHandler as the underlying code creates a HttpClientHandler and you need a WebRequestHandler e.g.

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

     return handler;
     }
}

Note that if you do this, it won't call OnApplyClientHandler so you will have to also allocate any other message handlers in this delegate. I can't easily check this out since I don't have access to a certificate secured site, but there's nothing in the code to suggest this won't work.

Patrick
  • 621
  • 2
  • 7
  • 21
0

Hope one of the below code snippets work fine!

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

vamsee
  • 31
  • 1
  • 9