Set wcf service credentials in config file for a service with endpoints created in code

5.8k views Asked by At

I want to be able to set the uri for a service endpoint in code while having the configuration for the security behaviour set in the config file.

The following gets me some of the way there, the service uses the correct binding configuration - but I cannot find a way to move the cert configuration into the config file.

Edit: note there was some confusion here - the config file configures the cert for Message level security and the ssl port controls the cert for Transport level - as per Richard Blewett's answer

var svc = new ServiceHost( typeof (MyService), new Uri(s));
svc.Authorization.PrincipalPermissionMode = 
                  PrincipalPermissionMode.UseWindowsGroups;
svc.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding("MyBinding"), "");
//svc.Credentials.ServiceCertificate.SetCertificate(
//    StoreLocation.LocalMachine,
//    StoreName.My,
//    X509FindType.FindBySubjectName,
//    "mycertname"
//    );

the commented out code is what I need to find some equivalent for in the config file

   <system.serviceModel>
     <services>
       <service name="MyNamespace.MyService" behaviorConfiguration="MyBehavior">
       </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="MyBinding">
          <security mode="Transport">
            <transport clientCredentialType="Windows"/>
          </security>
          <!-- Or for message level security
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
          -->
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>  

Edit: for posterity I have updated the question and answer to cover both message level and transport level as I need cater for both.

1

There are 1 answers

6
Richard Blewett On BEST ANSWER

For Message security this service behavior should give you what you need

<behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceCredentials>
            <serviceCertificate findValue="mycertname"
                                x509FindType="FindBySubjectName"
                                storeLocation="LocalMachine"
                                storeName="My"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
</behaviors>

However, you are using transport security - in other words HTTPS with wsHttpBinding. Therefore the cert is defined by the configuration of http.sys where you bind a cert to a port. On Windows 2008 you use netsh.exe to contorl and view this configuration. on Windows 2003 you use the much less usable tool httpcfg.exe