Few days ago I was working on a project that required to access a wiki page. Whenever I was trying to access the page via web browser then it was asking user/pwd to access the page. It was not like a login page where you will put your credentials and access the page. Rather it was coming from IIS for basic authentication.
If any site uses standard Log In Form then I can easily log in to the site using .NET/C#. For this I simply need to pass my user/pwd as POST data. For IIS basic authentication I need to provide extra information to the site in different way. Here is the code that I used for my purpose:
WebRequest webRequest = WebRequest.Create(finalUrl);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(finalUrl), “Basic”, new NetworkCredential(userName, password));
webRequest.Credentials = credentialCache;
webRequest.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
contentType = response.ContentType;
System.IO.Stream stream = response.GetResponseStream();
System.IO.StreamReader sReader = new System.IO.StreamReader(stream);
pageSource = sReader.ReadToEnd();
Look at the bold lines of this code segment. Here I’ve to mention that I’m going to create a “Basic” authentication as the second parameter of the credential cache and before requesting to the page I need to mention that it requires pre-authentication[webRequest.PreAuthenticate = true;]. This two options serve my purpose to authenticate basic IIS at first and then make my intended request to the site.
I hope this code block will also help you!