V
V
Vasily Vorobyov2015-10-01 15:55:46
C++ / C#
Vasily Vorobyov, 2015-10-01 15:55:46

Why doesn't the second POST request work in C#?

Bottom line: there is a django application in which you need to log in.
How I do it:
1. I send the first get request to the login url to get csrfmiddlewaretoken
2. I send a post request to the same url, I send this same token as a cookie and post data, and I also add user data to the post data.
3. As a result, I check: if a redirect occurred, authorization was successful
. How I did it in python and it worked:

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

How I did it in C# and it doesn't work, throwing request timed out on the second request:
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
tokenRequest.CookieContainer = new CookieContainer();
String token = ((HttpWebResponse)tokenRequest.GetResponse()).Cookies["csrftoken"].ToString().Split('=')[1];

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

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

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

byte[] data = Encoding.ASCII.GetBytes("username=" + tempEmail + "&password=" + tempPass + "&csrfmiddlewaretoken=" + token);
loginRequest.ContentLength = data.Length + 1;
loginRequest.Timeout = 3000;
loginRequest.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(tempEmail + ":" + tempPass)));
loginRequest.GetRequestStream().Write(data, 0, data.Length);
Debug.Log(loginRequest.Headers.ToString());
// вот здесь выкидывает request timed out
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);

I want it to work in C#. How to do it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question