Search code examples
c#wcfwcf-securitywcf-client

C#: method to add WCF authentication, username + SSL?


I've written both a WCF client and a remote internet WCF server.

The remote WCF server is running WPF hosted in a traditional Windows Service wrapper (i.e. not IIS).

Currently, its working perfectly with basic HTTP binding. I'm using Visual Studio 2010 + .NET 4.0 + C#.

Can anyone point me in the direction of the right steps to alter my code so that I can add username + SSL authentication?

EDIT:

At the service end, I've overridden UserNamePasswordValidator as follows:

public class CustomUserNameValidator : UserNamePasswordValidator
{
  public override void Validate(string userName, string password)
  {
    Console.WriteLine("Got to here");
  }
}

At the service end, I've specified a link to the username validation class:

  ServiceHost serviceHost = new ServiceHost(typeof(PhiFeedServer.PhiFeed)); // ,baseAddress);

  const bool passswordAuthentication = true;
  if (passswordAuthentication)
  {
    // These two lines switch on username/password authentication (see custom class "CustomUserNameValidator" in common file PhiFeed.svc.cs)
    // See http://msdn.microsoft.com/en-us/library/aa354513.aspx
    serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
    serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
  }

  // Start the service
  serviceHost.Open();

At the client end:

  EndpointAddress endpointAddress = new EndpointAddress("http://localhost:20000/PhiFeed?wdsl"); 
  BasicHttpBinding serviceBinding = new BasicHttpBinding();
  serviceBinding.ReceiveTimeout = new TimeSpan(0, 0, 120);
  proxy = new PhiFeedClient(serviceBinding, endpointAddress);

  proxy.ClientCredentials.UserName.UserName = "myusername";
  proxy.ClientCredentials.UserName.Password = "mypassword";

However, when I run everything, it never even calls the username validator - whats going on?


Solution

  • If i am getting this right, you will need to play around with service behaviour. I did that in 3.5 sp1 it should be the same in 4.0 i think.

    read this: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/7d589542-277a-404e-ab46-222794422233/