Friday, February 5, 2010

Access Denied Web service , asp.net , c#.net , vb.net ,Anonymous Authentication

Access Denied error message in web service


When trying call a web service you may receive the error message as

The request failed with HTTP status 401: Access Denied.

Description: An unhandled exception occurred during the execution of the current Web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The request failed with HTTP status 401: Access Denied.


The reason for this error is if the anonymous authentication is turned off you must give credentials before calling the web service. To resolve this issue you must use the credential property of the web service client proxy to set the security credentials for web service client authentication.

The ways to resolve this issue is explained below.

Assign the default credentials to the credential property of the webservice proxy class. To do this follow the following code.

myProxy.Credentials= System.Net.CredentialCache.DefaultCredentials;

Use the CredentialCache class to providecredentials for webservice client authentication. To do this first create an object CredentialCache class and again create an object of NetworkCredential which uses the specified username and password. To do this follow the following code.

In c#.net

//Create an instance of the CredentialCache class.
CredentialCache cache = new CredentialCache();

// Add a NetworkCredential instance to CredentialCache.
// Negotiate for NTLM or Kerberos authentication.
cache.Add( new Uri(myProxy.Url), "Negotiate", new NetworkCredential ("UserName", "Password", "Domain"));

//Assign CredentialCache to the Web service Client Proxy(myProxy) Credetials property.
myProxy.Credentials = cache;


In vb.net

'Create an instance of the CredentialCache class.
Dim cache As CredentialCache = New CredentialCache()

'Add a NetworkCredential instance to CredentialCache.
'Negotiate for NTLM or Kerberos authentication.
cache.Add(New Uri(myProxy.Url), "Negotiate", New NetworkCredential("UserName", "Password", "Domain"))

'Assign CredentialCache to the Web service Client Proxy(myProxy) Credetials property.
myProxy.Credentials = cache

1 comment: