I need some help from anyone that knows C#! I need to create a simple C# script that creates a web request and is able to sign in using HTTP authentication. I am testing the script on one of my websites that I put a password lock on (don't worry nothing confidential just password blocked for testing purposes): www.alienauthoritythegame.com
Username and password: edward tester
I have found several solutions on how to do this (including here on StackOverflow) but none of them work. Each code/method I tried includes a comment above it for the method I tried. None of these work. When I try to get a response from the web page, I got a 401 everytime. Any help is appreciated.
http_username = "edward";
http_password = "tester";
http_authentication = 1;
try
{
string url = "http://alienauthoritythegame.com";
Uri myUri = new Uri(url);
WebRequest request = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)request;
request.PreAuthenticate = true;
// Set up the credentials
if (http_authentication == 1)
{
// method 1: Doesn't work
NetworkCredential myNetworkCredential = new NetworkCredential(http_username, http_password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
// Method 2: doesn't work
ICredentials credentials = new NetworkCredential( "edward", "tester", "http://alienauthoritythegame.com"); //I used my username and password here
request.Credentials = credentials;
// Method 3: doesn't work
System.Net.NetworkCredential netCredential = new System.Net.NetworkCredential("edward", "tester", "http://alienauthoritythegame.com");
request.Credentials = netCredential;
// Method 4: doesn't work
string authInfo = http_username + ":" + http_password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
// Method 5: doesn't work
byte[] credentialBuffer = new UTF8Encoding().GetBytes("edward" + ":" + "tester");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
}
// Creates a 401 every time
WebResponse response = request.GetResponse();
}
catch (Exception webEx)
{
Response.Write(webEx.ToString());
}