Tuesday, February 06, 2007

Using Basic authorization with C# Web Service clients

Even if you really know you shouldn't, you might want to use Basic authorization to add a "secure-look-alike" feature to your web services. When trying to access such web services from C# I had some problems, apparently the Authorization of the HTTP header is not set when using

ICredentials creds = new NetworkCredential("username", "password");
wsService.Credentials = creds;
caiusService.PreAuthenticate = true;

in your C# code. The reason is that C# puts this information into the SOAP header, and NOT the HTTP header as you would expect.

It is not that hard to fix this though.
1) Open the Reference.cs file
2) override the GetWebRequest(Uri uri) method

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
//Modifiying the http header to include basic authentication
string username = "username";
string password = "password";
string auth = username + ":" + password;
byte[] binaryData = new Byte[auth.Length];
binaryData = System.Text.Encoding.UTF8.GetBytes(auth);
auth = Convert.ToBase64String(binaryData);
auth = "Basic " + auth;
System.Console.WriteLine("Adding Authoriation to http header: " + auth);

System.Net.WebRequest req = base.GetWebRequest(uri);
req.Headers["Authorization"] = auth;
return req;
}

And there you go.

0 Comments:

Post a Comment

<< Home