2

I am trying to set wsHttpBinding with username / password. The problem that I've ran into is how to set username / password?

I've set this:

binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
      binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

But where is the setting for username / password?

WSHttpBinding binding = new WSHttpBinding();
  binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
  binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;


  Type contractType = typeof(ITest);
  Type serviceType = typeof(Test);
  Uri httpUri = new Uri("http://localhost:8083/Test2");
  ServiceHost myServiceHost = new ServiceHost(serviceType, httpUri);

  ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
  smb.HttpGetEnabled = true;
  myServiceHost.Description.Behaviors.Add(smb);

  myServiceHost.Open();

Code:

namespace ConsoleApplication1
{
  [ServiceContract]
  interface ITest
  {
    [OperationContract]
    string Ping();
  }
}



namespace ConsoleApplication1
{
  class Test : ITest
  {
    public string Ping()
    {
      return "Pong - it works!";
    }
  }
}
FrenkyB
  • 6,625
  • 14
  • 67
  • 114

1 Answers1

1

By default WCF uses Windows users to authenticate. But you can plugin your own custom validator.

You need to create your class inherited from UserNamePasswordValidator and then tell WCF to use it:

myServiceHost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication
.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
myServiceHost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication
.CustomUserNamePasswordValidator = new MyCustomValidator();

See also this example and official MSDN documentation.

Igor Labutin
  • 1,406
  • 10
  • 10