0

I have been trying to get an HttpWebRequest or anything else to give me the HTML of a webpage with a required login. IN a normal browser you do something like:

http://username:password@someURL.com

However in C#, this fails with a 401 Unauthorized.

I have also tried to set the credentials but it also fails. I have tried enabling cookies, posing as a browser, I'm lost...

string credentials = _domain.UserInfo;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_domain);
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

** Another Try ****

System.Net.WebRequest req = System.Net.WebRequest.Create(_domain);
if (_domain.UserInfo.Length > 0)
{
    string[] creds = _domain.UserInfo.Split(new char[] { ':' });
    req.Credentials = new System.Net.NetworkCredential(creds[0], creds[1], _domain.Authority);
}

req.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
req.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
System.Net.HttpWebRequest _httpReq = (HttpWebRequest)req;
_httpReq.CookieContainer = new CookieContainer();
_httpReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
_httpReq.UnsafeAuthenticatedConnectionSharing = true;
System.Net.WebResponse resp = req.GetResponse();

What am I doing wrong?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Nick
  • 739
  • 11
  • 22

1 Answers1

0

This behavior is by design (see here.) and there doesn't seem to be an easy way to change this behavior. Instead you will need to put your credentials into a System.Net.NetworkCredentials object and set the Credentials property to that on your web request.

Yaur
  • 7,333
  • 1
  • 25
  • 36