Calling windows authenticated WCF service from c#

Viewed 1699

We have a WCF service which is windows authenticated. Binding is configured as below.

<basicHttpBinding>
    <binding textEncoding="utf-8" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
        <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" />            
        </security>
    </binding>
</basicHttpBinding>

I am trying to call the service from a test application as,

try
{
    BasicHttpBinding binding = new BasicHttpBinding();
    binding.ReceiveTimeout = new TimeSpan(10, 10, 00);
    binding.SendTimeout = new TimeSpan(10, 10, 00);
    binding.MaxReceivedMessageSize = Int32.MaxValue;
    binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
    EndpointAddress endpoint = new EndpointAddress("ServiceUrl");

    ChannelFactory<ICRMConnectorService> channelFactory = new ChannelFactory<ICRMConnectorService>(binding, endpoint);
    channelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
    var service = channelFactory.CreateChannel();

    service.TestMethod();
}
catch (Exception ex)
{
    throw ex;
}

The call is returning an error as, The remote server returned an error: (401) Unauthorized.

Can someone please help out?

3 Answers

You can create a client object from ServiceReference (that you have added in your application) for calling methods and where you can provide the windows credentials to access webservice.

For practical implementation Try this: WCF Service, Windows Authentication

Make sure the endpoint in the wcf service is configured something like this <endpoint address="" binding="wsHttpBinding" contract="IService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

Make sure that the method you are calling is using impersonation i.e. [OperationBehavior(Impersonation = ImpersonationOption.Required)] public void TestMethod() { }

I just checked myself, with your settings the server doesn't get caller identified. I'd say you'd rather switch to another binding which is able to use secure channel, for example BasicHttpsBinding. Latter, however, requires SSL certificate set up on server (netsh http add sslcert ...), and, probably, some validation in client (ServicePointManager.ServerCertificateValidationCallback). There is also a post on the same matter, yet it involves IIS.

Related