Home > C# > Accessing Protected Pages in C#

Accessing Protected Pages in C#

System.Net.WebRequest can be used to download a web resource in .Net code. Following is code to download a web resource in code:

String url = "http://domain.com/resource_url";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
WebResponse resp = req.GetResponse();
Stream Answer = resp.GetResponseStream();

This code works okay if the web resource is not protected and is public-ally accessible. But if the resource is protected using windows authentication, the code req.GetResponse() will return an Unauthorized exception.

To access a protected resource, we will need to use NetworkCredentials for the web request as shown in the following code:

String url = "http://domain.com/resource_url";
String user = "window_auth_username";
String pwd = "window_auth_password";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true; //Tell the server that request is authenticated
req.Credentials = new NetworkCredential(user, pwd, "http://domain.com"); //Link the credentials
//Remaining code will remain the same.

WebResponse resp = req.GetResponse();
Stream Answer = resp.GetResponseStream();
Advertisements
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: