Introduction
When we consume a web service in .NET, the default user credentials passed on is that of the anonymous user.If the web service is configured to allow access to anonymous users, then things will be fine.But at times the web service will be configured for Integrated Windows Authentication. In such case valid credentials has to be passed.
Failing to pass the correct credentials will result in an error.
In the code shown below the following error will be thrown at the line where the TestWebMethod is executed.
Code:
TestWebServiceClient webServiceClient = new TestWebServiceClient();
webServiceClient.TestWebMethod();
webServiceClient.TestWebMethod();
System.Net.WebException: The request failed with HTTP status 401: Unauthorized
Thus, in an intranet environment, it would probably make sense to pass the current windows user’s credentials.
In an internet scenario, where the call is made over the internet, the credentials have to be passed explicitly.
Passing Current Windows credentials:
The property Credentials of the proxy class in the web service client has to be set with the correct credentials.To set the current windows credentials we use CredentialCache.DefaultCredentials.
Code:
TestWebServiceClient webServiceClient = new TestWebServiceClient();
webServiceClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
webServiceClient.TestWebMethod();
webServiceClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
webServiceClient.TestWebMethod();
Passing Explicit Windows credentials:
For this the property Credentials of the proxy class in the web service client has to be set with the correct NetworkCredential objectCode:
TestWebServiceClient webServiceClient = new TestWebServiceClient();
System.Net.NetworkCredential objCredential = new System.Net.NetworkCredential(UserName, Password, Domain);
webServiceClient.Credentials = objCredential;
webServiceClient.TestWebMethod();
System.Net.NetworkCredential objCredential = new System.Net.NetworkCredential(UserName, Password, Domain);
webServiceClient.Credentials = objCredential;
webServiceClient.TestWebMethod();