I am trying to make a request to a web page using WebRequest class in .net. The url that I am trying to read requires Windows Authentication due to which I get an unauthorised exception. How can I pass a windows credentials to this request so that it can authenticate.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( "http://myapp/home.aspx" ); request.Method = "GET"; request.UseDefaultCredentials = false; request.PreAuthenticate = true; request.Credentials = new NetworkCredential( "username", "password", "domain" ); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Raises Unauthorized Exception this.Response.Write( response.StatusCode );
The above code returns the following error.
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
I noticed one thing while checking the exception details is that the url that I am trying to access is redirecting to a different url which is prompting me to provide the NT login details. I believe that the credentials should get forwarded to this url as well. But apparently it is not happening.
On the taskbar, click Start, and then click Control Panel. In Control Panel, click Programs and Features, and then click Turn Windows Features on or off. Expand Internet Information Services, then World Wide Web Services, then Security. Select Windows Authentication, and then click OK.
You can use Windows Authentication when your server runs on a corporate network using Active Directory domain identities or Windows accounts to identify users. Windows Authentication is best suited to intranet environments where users, client apps, and web servers belong to the same Windows domain.
To set up your ASP.NET application to work with Windows-based authentication, begin by creating some users and groups. Within your Windows operating system, go to "Control Panel" -> "User Accounts" -> "Manage another account" -> "Create a new account" then choose "Add or Remove User".
You should use Credentials property to pass the windows credentials to the web service.
If you wish to pass current windows user's credentials to the service then
request.Credentials = CredentialCache.DefaultCredentials;
should do the trick. Otherwise use NetworkCredential as follows:
request.Credentials = new NetworkCredential(user, pwd, domain);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With