我尝试在这里和其他网页上搜索了很多答案,但我花了一整天时间仍然无法做到。
一个朋友建立一个django后端,他让我建立一个Android应用程序连接到后端,最好的结果是这个Android Client login to a Django server, how to pass crsf :|但是我无法让它工作,我从服务器获得CSRF但后来我尝试使用URLConnection,HttpClient,HttpPost,还有很多其他例子而且没什么。
现在我的代码是:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://URL-TO-SERVER/");
String CSRFTOKEN = getCsrfFromUrl("http://URL-TO-SERVER/");
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", mEmail));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", CSRFTOKEN));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("X-CSRFToken", CSRFTOKEN);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie csrf_cookie = new BasicClientCookie("X-CSRFToken", CSRFTOKEN);
csrf_cookie.setDomain("URL-SERVER");
cookieStore.addCookie(csrf_cookie);
// Create local HTTP context - to store cookies
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// Execute HTTP Post Request
HttpResponse response = null;
try {
Log.e(TAG,"Token: "+CSRFTOKEN);
response = httpclient.execute(httppost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getAllHeaders());
try {
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
并且getCsrfFromUrl()来自链接。并在
nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", CSRFTOKEN));
我尝试更改csrftoken的密钥,对于X-CSRFToken,我仍然不知道什么是错的,或者我怎么能让它工作,可能是后端的问题?功能或密钥丢失了? 我尝试做的是登录我需要输入用户名和密码的页面,然后重新收集响应以查看谁输入并使用该数据。
答案 0 :(得分:0)
你使用的getCsrfFromUrl
是错误的,它返回在响应中找到的第一个cookie而不检查它是否是CSRF cookie,这个应该有效:
public String getCsrfFromUrl(String url) {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClientStatic.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
List<Cookie> cookies = httpClientStatic.getCookieStore().getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("csrftoken")) {
return cookie.getValue();
}
}
return null; // Or throw exception.
}
然后,您可以将返回的值用作POST参数。
尽管如您所链接问题的评论中所述,您不应该为Android应用访问的视图提供CSRF保护。