Sunday, December 17, 2006

Call web service from C# client using basic authentication

The C# class Credentials is used to put authentication information into the SOAP header, not the HTTP header, which would lead to some problem when calling a java-based web service.
In order to invoke web service protected by basic authentication from a C# client, we must override the GetWebRequest() method.
The solution is as follows:
protected override System.Net.WebRequest GetWebRequest(Uri uri){
System.Net.WebRequest request = base.GetWebRequest (uri);
string username = "Test";
string password = "Test";
string auth = username + ":" + password;
byte[] binaryData = new Byte[auth.Length];
binaryData = Encoding.UTF8.GetBytes(auth);auth = Convert.ToBase64String(binaryData);
auth = "Basic " + auth;
request.Headers["AUTHORIZATION"] = auth;
return request;
}
2 related posts can be found at: thescripts developer network , Clinton Davidson's blog .

1 comment:

Zhang Yelei said...

The overriding can be done in the following code:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, "Basic");
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes( networkCredentials.UserName + ":" + networkCredentials.Password);
request.Headers["Authorization"] = "Basic" +Convert.ToBase64String(credentialBuffer);
} else{
throw new ApplicationException("No network credentials");
}
}
return request;
}
The client code should be:
try {
WMTest2.WMTest.WMTestService WMTestService = new WMTest2.WMTest.WMTestService();
NetworkCredential netCredential = new NetworkCredential("WMTest", "WMTest");
Uri uri = new Uri(WMTestService.Url);
ICredentials credentials =netCredential.GetCredential(uri, "Basic");
WMTestService.Credentials = credentials;
WMTestService.PreAuthenticate = true;
String oString = WMTestService.WMTestFlow("Hello");
MessageBox.Show(oString);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}