Search code examples
c#web-serviceswcfbasic-authentication

Consuming web service with c# and basic authentication


I want to consume a web service with this code:

WebService.GenRelClient client = new WebService.GenRelClient();
client.ClientCredentials.UserName.UserName = @"UserName";
client.ClientCredentials.UserName.Password = @"Password";
var response = client.returnString("test");

And my config looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="GenRelClientPortBinding">
        <security mode="TransportCredentialOnly">
          <transport clientCredentialType="Basic" />
        </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint
          address="http://ws.domain.com/GenRel/GenRel"
          binding="basicHttpBinding"
          bindingConfiguration="GenRelClientPortBinding"
          contract="WebService.GenRelClientPort"
          name="GenRelClientPort" />
    </client>
  </system.serviceModel>
</configuration>

The request is sent to the web service and the response is sent back with incorrect message about that it need Basic Authentication because the request was sent probably without credentials, so I don't know where is the mistake.

Thank you for your help


Solution

  • For you to be able to call the web-service you will need to add security information to the SOAP header.

    Click here to read an MSDN article that explains the basic principle.

    Take a look at the code sample below and see if it solves your problem:

     var client = new WCClient();  
     using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
     {
         var httpRequestProperty = new HttpRequestMessageProperty();
         httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " +
                      Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" +
                      client.ClientCredentials.UserName.Password));
         OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
    
         client.DoSomething();
     }