如何在django应用中使用c#进行身份验证

本文关键字:身份验证 django 应用 | 更新日期: 2023-09-27 18:15:20

我有一个python脚本:

import requests
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

carkit。kg/-是django app中的登录url。如果认证成功,脚本打印一个url,否则打印另一个。我试着用c#重写这个脚本(Unity3D游戏):

//get token
string url = "http://carkit.kg";
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(url);
tokenRequest.CookieContainer = new CookieContainer();
HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
String token = tokenResponse.Cookies["csrftoken"].ToString().Split('=')[1];
//login 
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url);
loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token, "/", "carkit.kg"));
String postData = "username=" + tempEmail;
postData += "&password=" + tempPass;
postData += "&csrfmiddlewaretoken=" + token;
byte[] data = Encoding.ASCII.GetBytes(postData);
loginRequest.ContentLength = data.Length + 1;
Debug.Log(data.Length);
    loginRequest.Timeout = 3000;
    String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(tempEmail + ":" + tempPass));
    loginRequest.Headers.Add("Authorization", "Basic " + encoded);
loginRequest.GetRequestStream().Write(data, 0, data.Length);
loginRequest.PreAuthenticate=true;
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();

但是我得到错误411或超时的请求。如何在c#代码中获得与python相同的结果?

如何在django应用中使用c#进行身份验证

我将django rest api url设置为简单的post请求目的地,django在data中返回token。