Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a web request to a web page which requires windows authentication

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.

like image 283
Hemanshu Bhojak Avatar asked Aug 25 '10 05:08

Hemanshu Bhojak


People also ask

How do I use Windows Authentication on a Web application?

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.

Can we use Windows Authentication in Web API?

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.

How do you implement Windows Authentication How do you specify roles and permissions to the users?

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".


Video Answer


1 Answers

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); 
like image 198
VinayC Avatar answered Nov 06 '22 17:11

VinayC