basicHttpBinding with basic authentication send first request with no user/pass data

2.2k Views Asked by At

When using WCF basicHttpBinding with basic authentication, I notice that the first request after IIS reset is sent without user/pass data (without Authorization: Basic .... Header data)

Code:

client.ClientCredentials.UserName.UserName = "myUserName";
client.ClientCredentials.UserName.Password = "myPassword";
string anything = client.getValue(@"anyParam..");  

Config:

<basicHttpBinding>
    <binding name="ServiceNameHereServiceBinding" >
        <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic" proxyCredentialType="None"  
                    realm="">
            </transport>
        </security>
    </binding>
</basicHttpBinding>

After monitor by Fidler, I found that, the first request Always return 401 (go without Authentication header at all), then another request comes out and return 505 error. After that the service will work good for all further requests.

1

There are 1 best solutions below

0
Tarek El-Mallah On

I found the solution and I thought I may share it with you, it may help.

The solution is here http://plainoldstan.blogspot.ca/2008/07/avoid-http-401-roundtrip-with-adding.html by Stanislav Dvoychenko

It's by simply create the basic authentication header yourself, instead of depend on the Client to do so. because out of the box client will consider end point is Pre-Authenticated already.

// Assign client.ClientCredentials.UserName.UserName and client.ClientCredentials.UserName.Password 
SetupClientAuthentication(); 

HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); 

httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + 
    Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + 
    client.ClientCredentials.UserName.Password));

using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) 
{ 
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = 
        httpRequestProperty;

    // Invoke client 
}