Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a Web Service which requires a certificate in C#?

I need to communicate with a third party which has a .asmx web service. This web service is using https. I have the required certificate (.pfx).

When first trying to add this service using Add Service Reference in Visual Studio, I got an error. I got passed this error by importing the certificate into the Personal store. After I did that, I tried to add the Service Reference again and it works. So now I can create an instance of the web service. Nice.

But now I want to invoke the service. And when I do that I get this error:

302 Notification: Digital Certificate Missing

So how can I tell my service to use the right certificate?

like image 220
Martijn Avatar asked Mar 23 '16 14:03

Martijn


People also ask

How do you implement certificate based authentication in C#?

Open “Power Shell” as an administrator and run the below command: New-SelfSignedCertificate -DnsName "localhost", "localhost" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date). AddYears(10) -FriendlyName "CAlocalhost" -KeyUsageProperty All -KeyUsage CertSign, CRLSign, DigitalSignature.

What is HTTP client certificate?

In cryptography, a client certificate is a type of digital certificate that is used by client systems to make authenticated requests to a remote server. Client certificates play a key role in many mutual authentication designs, providing strong assurances of a requester's identity.


2 Answers

I finally managed to fix my problem as follows:

var service = new Service1SoapClient();
service.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.TrustedPublisher, X509FindType.FindByIssuerName, "name_of_issuer");
((BasicHttpBinding)service.Endpoint.Binding).Security.Mode = BasicHttpSecurityMode.Transport;
((BasicHttpBinding)service.Endpoint.Binding).Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

Please use Certificate.pfx and install it with password.

like image 82
Martijn Avatar answered Oct 20 '22 01:10

Martijn


Try adding this before getting the request stream:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
request.ProtocolVersion = HttpVersion.Version10;
request.ClientCertificates.Add(new X509Certificate2("YourPfxFile(full path).pfx", "password for your pfx file");

Depending on your security requirements and environment, you may need to use a different SecurityProrocolType value.

like image 41
Kevin Avatar answered Oct 19 '22 23:10

Kevin