Sunday, July 13, 2008

Avoid HTTP 401 roundtrip with adding Basic Authentication headers to the WCF HTTP Request

This is just quick and dirty note onto how to fix the issue with request-challenge-request roundtrip happening when Basic authentication is used for the wcf client-server authentication.

Per standard, client sends first request without basic authentication header, server responds with http 401 response with www-authenticate header.

The common understanding for the HttpWebRequest was that is has a PreAuthenticate property that would set basic authentication header for the first request and avoid roundtrip.

Although, I can confirm that via reflector one can see that wcf sets PreAuthenticate to be true in case when basic authentication is setup via binding. And it doesn't make it to send first request with a basic authentication header.

Just to flush out the quick snippet for avoiding the round trip:

// 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
}

This is definitely not the only option to set the header see Nicholas Allen's recent entry on setting headers: http://blogs.msdn.com/drnick/archive/2008/07/08/adding-headers-to-a-call-http-version.aspx

 

Post a Comment