C# - Trying to login using webrequest but webresponse returning the same html

355 Views Asked by At

I'm trying to login to a website through webrequest, but the webresponse is returning the same html of the login page.

CookieContainer cookies = new CookieContainer();
String postData = "vb_login_username=myusername&vb_login_password=mypassword";
byte[] send = Encoding.Default.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("domain url here"));
        request.CookieContainer = cookies;
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.Timeout = 30000;
        request.ContentLength = send.Length;
        Stream stream = request.GetRequestStream();
        stream.Write(send, 0, send.Length);
        stream.Flush();
        stream.Close();


   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            foreach (Cookie cook in response.Cookies)
            {
                cookies.Add(cook);
                Console.WriteLine(cook.Name+ cook.Value+ cook.Path+ cook.Domain);
            }
            StreamReader reader = new StreamReader(response.GetResponseStream());
            String result = reader.ReadToEnd();
            Console.WriteLine(result);
2

There are 2 best solutions below

2
On

Unfortunately, it is not so easy with this site. At first look at <form> tag:

<form onsubmit="md5hash(vb_login_password, vb_login_md5password, vb_login_md5password_utf, 0)" method="post" action="login.php?do=login" id="navbar_loginform">

Before submit it calls md5hash function to make a hash of password. Then in POST data after trying to log in you can see the vb_login_md5password and vb_login_md5password_utf parameters, but simple vb_login_password is empty.

1
On

While in most cases HTML returned in the request can be easily used as an indication of whether you managed to log in or not, you should not rely on it as a 100% sure method - I remember one particular website which, as far as non-browser HTTP requests were concerned, was returning pretty much the same HTML for a standard GET request and for a POST log in request. Instead what you should do is, after sending POST, send an additional GET request to one of the pages that would be normally accessible only after logging in. If the response received indicates that you managed to reach it (and not some error page or redirect), you know you are logged in.

It's generally very hard if not impossible to help you without knowing what website you want to log in to, as the process varies between them. Maybe it's necessary to start with a standard GET request to receive initial cookies first? Maybe some additional information is necessary to include in the headers? Maybe you have a typo somewhere in your POST content? It can be many different reasons.