4

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.

Peter
  • 9,643
  • 6
  • 61
  • 108
  • You need to make sure you close/dispose the `response` -- or put it in a `using()` block. Are you reusing the same cookie container on subsequent requests? – debracey Mar 06 '12 at 01:30
  • @debracey: I am using the same cookie container, the cookie container is a class level private variable which is reused for each HttpPost. I tweaked my code to use Using blocks and updated the code in my question, no change. – Peter Mar 06 '12 at 01:48

3 Answers3

6

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);
Community
  • 1
  • 1
eandersson
  • 25,781
  • 8
  • 89
  • 110
  • How did you verify it was working? When I run this code I see "Hey Anonymous!" in the response, and I am not logged in. – Peter Jul 20 '12 at 21:34
  • Yea, I am getting the same and that is why I updated my answer earlier. I'll update my answer soon. – eandersson Jul 20 '12 at 21:36
  • @Peter Ok, updated the answer. I had a major typo in the code `username` => `usrname`. Also, make sure to update the `CookieAwareWebClient` function as I updated it as well. – eandersson Jul 20 '12 at 22:41
  • I'll let you know as soon as I've had the chance to test it in my code to make sure it's working as expected. – Peter Jul 20 '12 at 22:44
  • Ok cool. I hope it works, if anything I love coding haha :D btw if you dont already make sure to get a HTTP Debugging Proxy like Fiddler, helps a lot. – eandersson Jul 20 '12 at 22:46
  • Sorry to have to tell you... but I can only get this to work with .NET 4. In .Net 3.5 and Mono 2 it doesn't work. I just checked and with the addition of System.Net.ServicePointManager.Expect100Continue = false the original code I posted also works in .NET 4, but not in 3.5. – Peter Jul 21 '12 at 02:52
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14207/discussion-between-peter-and-fuji) – Peter Jul 21 '12 at 02:59
  • Ah ok that was never mentioned in the original question. – eandersson Jul 21 '12 at 03:41
  • True, the version of .NET was not mentioned. I posted some comments in the chat window, maybe they will be helpful – Peter Jul 21 '12 at 03:49
  • @Peter I have updated with a working example for 3.5! It's now 7AM here lol so hopefully this will work for you, but it's dirty as ****. – eandersson Jul 21 '12 at 05:17
  • Not sure why using an empty UploadValues worked at 7AM last night, but it doesn't today. I updated the example 3.5 code. – eandersson Jul 21 '12 at 13:44
  • So far so good with my testing. Whether it works on Mono or not isn't important for this question, just .Net 3.5. Another day or so and I should know for certain that it's golden. Thanks so much for all your effort!!! – Peter Jul 22 '12 at 02:10
3

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;
DROP TABLE users
  • 1,955
  • 14
  • 26
SynXsiS
  • 1,860
  • 10
  • 12
  • When I try manually adding the cookies it looks like they are already there, or the ones there just get overwritten (either way the cookie count stays the same before and after the add). It is doing a redirect and I have tried the code with and without the AllowAutoRedirect flag at true/false but it doesn't change anything. – Peter Mar 06 '12 at 03:35
  • Try running fiddler (http://www.fiddler2.com/fiddler2/) while making the request to see if the cookies really are being set. You may have to tell your code to use the proxy. You can do that by calling 'req.Proxy = new WebProxy("127.0.0.1", 8888);' – SynXsiS Mar 06 '12 at 04:14
2

The Python you reference uses a different referrer (http://wallbase.cc/start/). It is also followed by another post to (http://wallbase.cc/user/adult_confirm/1). Try the other referrer and followup with this POST.

I think you are authenticating correctly, but that the site needs more info/assertions from you before proceeding.

Les
  • 10,335
  • 4
  • 40
  • 60
  • http://wallbase.cc/user/adult_confirm/1 is used to confirm that you want to see non-safe for work type wallpapers. If you use a tool such as Fiddler or Chromes developer view you will see that this URL is never hit during the authentication process. I'll try it with the alternate referrer, but I'm pretty sure that using /start/ is outdated and that I've already tried it. – Peter Jul 20 '12 at 21:36