Search code examples
wcfwcf-security

Can you define what certificate a WCF Service uses?


We have multiple programs hitting one WCF Service. When a client sends a message they get to define both a client certificate and a service certificate. To do signing and encryption. As far as I know a service can set both at start up. But i'm finding difficulty on how a service would check certificates on a per request basis.

If program A uses a certificate and program B uses a different certificate. Is there a way to tell WCF how to look up those certs without using the windows certificate store? I know how to load a X509Certificate2 from a file but can't seem to find what piece needs to be overridden to tell it to use a specific cert based on what is coming in. Everything I have done so far looks for that clients cert in the cert store. Business rules would rather we placed them somewhere else that we are encrypting. I would like program A's request to use one file and program B's request to use another that I can specify.


Solution

  • In order to do client authentication, you actually need a certificate + a private key, i.e., not just a certificate.

    You need a .PFX file that contains both a certificate and its corresponding private key. PFX are password protected.

    Here is a sample code:

    Client client = new Client();
    
    var cert = new X509Certificate2(File.ReadAllBytes("c:\\certificate_with_key.pfx"), "pfx_password");
    
    client.ClientCredentials.ClientCertificate.Certificate = cert;