V
V
Vasily Vorobyov2015-10-01 19:32:55
Django
Vasily Vorobyov, 2015-10-01 19:32:55

Why can't I log in to my django app using C#?

carkit.kg - LOGIN_URL of the django app where I'm trying to login using C# with the following code (throws a 403 Forbidden error):

HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg/login");
  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/login");

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

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

  loginRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  loginRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
  loginRequest.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
  loginRequest.Headers.Add("Cache-Control", "max-age=0");
  loginRequest.KeepAlive = true;
  loginRequest.ContentLength = 82;
  //loginRequest.ContentType = "application/x-www-form-urlencoded";
  //loginRequest.Headers.Add("Host", "carkit.kg");
  loginRequest.Headers.Add("Origin", "http://carkit.kg");
  loginRequest.Referer = "http://carkit.kg/login";
  loginRequest.Headers.Add("Upgrade-Insecure-Requests", "1");
  loginRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
  loginRequest.Headers.Add("XCompress", "null");
  loginRequest.Timeout = 3000;
  loginRequest.Headers.Add("X-CSRFToken", token);

  byte[] data = Encoding.ASCII.GetBytes("username=" + username + "&password=" + password + "&csrfmiddlewaretoken=" + token);
  loginRequest.GetRequestStream().Write(data, 0, data.Length);
  loginRequest.GetRequestStream().Close();
  HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
  Debug.Log(authResponse.ResponseUri);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Mozhaykin, 2015-10-02
@smozhaykin

Do you have working python code? Compare both requests (python and c#) with wireshark and see what is missing in the second case.

S
sim3x, 2015-10-04
@sim3x

It is necessary to collect and send csrf token from cookies

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question