Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems authenticating to website from code

I am trying to write code that will authenticate to the website wallbase.cc. I've looked at what it does using Firfebug/Chrome Developer tools and it seems fairly easy:

Post "usrname=$USER&pass=$PASS&nopass_email=Type+in+your+e-mail+and+press+enter&nopass=0" to the webpage "http://wallbase.cc/user/login", store the returned cookies and use them on all future requests.

Here is my code:

    private CookieContainer _cookies = new CookieContainer();

    //......

    HttpPost("http://wallbase.cc/user/login", string.Format("usrname={0}&pass={1}&nopass_email=Type+in+your+e-mail+and+press+enter&nopass=0", Username, assword));

    //......


    private string HttpPost(string url, string parameters)
    {
        try
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
            //Add these, as we're doing a POST
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            ((HttpWebRequest)req).Referer = "http://wallbase.cc/home/";
            ((HttpWebRequest)req).CookieContainer = _cookies;

            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
            req.ContentLength = bytes.Length;
            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length); //Push it out there
            os.Close();

            //get response
            using (System.Net.WebResponse resp = req.GetResponse())
            {

                if (resp == null) return null;
                using (Stream st = resp.GetResponseStream())
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(st);
                    return sr.ReadToEnd().Trim();
                }
            }
        }
        catch (Exception)
        {
            return null;
        }
    }

After calling HttpPost with my login parameters I would expect all future calls using this same method to be authenticated (assuming a valid username/password). I do get a session cookie in my cookie collection but for some reason I'm not authenticated. I get a session cookie in my cookie collection regardless of which page I visit so I tried loading the home page first to get the initial session cookie and then logging in but there was no change.

To my knowledge this Python version works: https://github.com/sevensins/Wallbase-Downloader/blob/master/wallbase.sh (line 336)

Any ideas on how to get authentication working?

Update #1
When using a correct user/password pair the response automatically redirects to the referrer but when an incorrect user/pass pair is received it does not redirect and returns a bad user/pass pair. Based on this it seems as though authentication is happening, but maybe not all the key pieces of information are being saved??

Update #2

I am using .NET 3.5. When I tried the above code in .NET 4, with the added line of System.Net.ServicePointManager.Expect100Continue = false (which was in my code, just not shown here) it works, no changes necessary. The problem seems to stem directly from some pre-.Net 4 issue.

like image 202
Peter Avatar asked Dec 21 '22 01:12

Peter


2 Answers

This is based on code from one of my projects, as well as code found from various answers here on stackoverflow.

First we need to set up a Cookie aware WebClient that is going to use HTML 1.0.

public class CookieAwareWebClient : WebClient
{
    private CookieContainer cookie = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.ProtocolVersion = HttpVersion.Version10;
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = cookie;
        }
        return request;
    }
}

Next we set up the code that handles the Authentication and then finally loads the response.

var client = new CookieAwareWebClient();
client.UseDefaultCredentials = true;
client.BaseAddress = @"http://wallbase.cc";

var loginData = new NameValueCollection();
loginData.Add("usrname", "test");
loginData.Add("pass", "123");
loginData.Add("nopass_email", "Type in your e-mail and press enter");
loginData.Add("nopass", "0");
var result = client.UploadValues(@"http://wallbase.cc/user/login", "POST", loginData);

string response = System.Text.Encoding.UTF8.GetString(result);

We can try this out using the HTML Visualizer inbuilt into Visual Studio while staying in debug mode and use that to confirm that we were able to authenticate and load the Home page while staying authenticated.

Success

The key here is to set up a CookieContainer and use HTTP 1.0, instead of 1.1. I am not entirely sure why forcing it to use 1.0 allows you to authenticate and load the page successfully, but part of the solution is based on this answer. https://stackoverflow.com/a/10916014/408182

I used Fiddler to make sure that the response sent by the C# Client was the same as with my web browser Chrome. It also allows me to confirm if the C# client is being redirect correctly. In this case we can see that with HTML 1.0 we are getting the HTTP/1.0 302 Found and then redirects us to the home page as intended. If we switch back to HTML 1.1 we will get an HTTP/1.1 417 Expectation Failed message instead. Fiddler

There is some information on this error message available in this stackoverflow thread. HTTP POST Returns Error: 417 "Expectation Failed."

Edit: Hack/Fix for .NET 3.5

I have spent a lot of time trying to figure out the difference between 3.5 and 4.0, but I seriously have no clue. It looks like 3.5 is creating a new cookie after the authentication and the only way I found around this was to authenticate the user twice.

I also had to make some changes on the WebClient based on information from this post. http://dot-net-expertise.blogspot.fr/2009/10/cookiecontainer-domain-handling-bug-fix.html

public class CookieAwareWebClient : WebClient
{
    public CookieContainer cookies = new CookieContainer();
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        var httpRequest = request as HttpWebRequest;
        if (httpRequest != null)
        {
            httpRequest.ProtocolVersion = HttpVersion.Version10;
            httpRequest.CookieContainer = cookies;

            var table = (Hashtable)cookies.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cookies, new object[] { });
            var keys = new ArrayList(table.Keys);
            foreach (var key in keys)
            {
                var newKey = (key as string).Substring(1);
                table[newKey] = table[key];
            }
        }
        return request;
    }
}

var client = new CookieAwareWebClient();

var loginData = new NameValueCollection();
loginData.Add("usrname", "test");
loginData.Add("pass", "123");
loginData.Add("nopass_email", "Type in your e-mail and press enter");
loginData.Add("nopass", "0");

// Hack: Authenticate the user twice!
client.UploadValues(@"http://wallbase.cc/user/login", "POST", loginData);
var result = client.UploadValues(@"http://wallbase.cc/user/login", "POST", loginData);

string response = System.Text.Encoding.UTF8.GetString(result);
like image 188
20 revs Avatar answered Jan 07 '23 03:01

20 revs


You may need to add the following:

//get response
using (System.Net.WebResponse resp = req.GetResponse())
{
    foreach (Cookie c in resp.Cookies)
        _cookies.Add(c);
    // Do other stuff with response....
}

Another thing that you might have to do is, if the server responds with a 302 (redirect) the .Net web request will automatically follow it and in the process you might lose the cookie you're after. You can turn off this behavior with the following code:

req.AllowAutoRedirect = false;
like image 36
SynXsiS Avatar answered Jan 07 '23 05:01

SynXsiS