user1327064
user1327064

Reputation: 4337

How to pass user credentials to web service?

I am consuming a webservice using WSDL in windows application. When I try to use method, i get the following error:-

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was '"

{"The remote server returned an error: (401) Unauthorized."}

I have user credentials but don't know how to pass it using c# code in windows application.

Upvotes: 14

Views: 63987

Answers (3)

alanextar
alanextar

Reputation: 1314

In method where you create client add following code

private void SetAuthCredentials<T>(ClientBase<T> client) where T : class
{
    client.ClientCredentials.UserName.UserName = _config.Login;
    client.ClientCredentials.UserName.Password = _config.Password;
    var httpBinding = (BasicHttpBinding)client.Endpoint.Binding;
    httpBinding.Security.Transport.ClientCredentialType =
        HttpClientCredentialType.Basic;
    httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
}

This adds the header for Basic authentication scheme to the client

Upvotes: 0

user1327064
user1327064

Reputation: 4337

Here is the how it is working for me:-

Config file setting looks like this:-

<configuration>
    <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="bindingName"  >
              <security mode="TransportCredentialOnly">
                <transport clientCredentialType="Basic" proxyCredentialType="None" realm=""/>
                <message clientCredentialType="UserName" algorithmSuite="Default"/>
              </security>
            </binding>

          </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://10.10.10.10:1880/testpad/services/Testwebservice"
                binding="basicHttpBinding" bindingConfiguration="bindingName"
                contract=testService.GetData" name="test_Port1" />
        </client>
    </system.serviceModel>
</configuration>

and here i am passing user credentials:-

 var ser = new GetDataClient();
 ser.ClientCredentials.UserName.UserName = "userid";
 ser.ClientCredentials.UserName.Password = "Pa$$word1";

Upvotes: 13

Jay
Jay

Reputation: 6294

You can try to genereate your service client proxy using the method mentioned here. Once you have an instance of your WCF client proxy, it will have a property ClientCreditials which you can populate as needed. Hope this helps.

Upvotes: 0

Related Questions