Vassily
Vassily

Reputation: 5428

Django server returns 403 Forbidden while logging in via C#

There is a code I'm using to authenticate in django app with "/" as login url:

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/"), "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) {Domain="carkit.kg"});
Debug.Log(token);
byte[] data = Encoding.UTF8.GetBytes("username=" + tempEmail + "&password=" + tempPass + "&csrfmiddlewaretoken=" + token);
loginRequest.ContentLength = data.Length;
loginRequest.Timeout = 10000;
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.LogWarning(loginRequest.ToString());

//There is 403 error
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);

Token request is ok, but post request returns 403 error. I'm guessing that the problem is in incorrect cookies or post data but I cant find it out.

Upvotes: 0

Views: 234

Answers (1)

Kamal Singh
Kamal Singh

Reputation: 531

You need to send a X-CSRFToken header with the csrf token.

X-CSRFToken:<csrftoken cookie value>

(I don't know how to do it with C# )

Upvotes: 1

Related Questions