Search code examples
c#posthttp-request

403 error in Unity3D C#


I have the following code:

HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
tokenRequest.CookieContainer = new CookieContainer();
string token = "";
using (var response = (HttpWebResponse)tokenRequest.GetResponse()) {
    token = response.Cookies["csrftoken"].ToString().Split('=')[1];
}

HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");

var cache = new CredentialCache();
cache.Add(new Uri("http://carkit.kg/"), "Basic", new NetworkCredential(tempEmail, tempPass));
loginRequest.Credentials = cache;
loginRequest.PreAuthenticate = true;

loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token) {Domain="carkit.kg"});
Debug.Log(token);

byte[] data = Encoding.UTF8.GetBytes("username=" + tempEmail + "&password=" + tempPass + "&csrfmiddlewaretoken=" + token);

//loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.ContentLength = data.Length;
loginRequest.Timeout = 3000;
loginRequest.GetRequestStream().Write(data, 0, data.Length);
Debug.LogWarning(loginRequest.Headers.ToString());
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);

authResponse.ResponseUri should be http://carkit.kg if password is incorrect and carkit.kg/game in other case.

last request have same url as first, but I'm getting 403 error on second one.

There is a code on python that makes work that I want C# code able to do:

import urllib2

main_page_request = requests.get('http://carkit.kg/')
csrf_cookie = main_page_request.cookies.get('csrftoken', '')

r = requests.post('http://carkit.kg/', data={u'username': u'admin', u'password': u'admin', 'csrfmiddlewaretoken': csrf_cookie }, cookies={'csrftoken': csrf_cookie})
print r.url

Solution

  • My guess is you are not entering the credential information in the right format. I would use a CredentialCache and set PreAuthenticate=true Here is code for that:

    var cache = new CredentialCache();
    cache.Add(new Uri(uri), "Digest", new NetworkCredential(username, password));
    httpRequest.Credentials = cache;
    httpRequest.PreAuthenticate = true;
    

    For fixing 411 error try this: Why I get 411 Length required error?

    Why are you adding 1 to data.length? I would try

    loginRequest.ContentLength = data.Length;