【发布时间】:2013-12-19 12:45:50
【问题描述】:
在 Android 应用程序中使用 POST 方法连接 django 服务器时出现 CSRF 失败。 httpResponse 如下:
禁止 (403)
CSRF 验证失败。请求中止。
失败原因:
CSRF cookie 未设置。
一般来说,当有真正的跨站请求伪造时,或者没有正确使用 Django 的 CSRF 机制时,就会发生这种情况。对于 POST 表单,您需要确保: 您的浏览器正在接受 cookie。 视图函数使用 RequestContext 作为模板,而不是 Context。 在模板中,每个针对内部 URL 的 POST 表单内都有一个 {% csrf_token %} 模板标签。 如果您不使用 CsrfViewMiddleware,那么您必须对使用 csrf_token 模板标签的任何视图以及接受 POST 数据的视图使用 csrf_protect。 您看到此页面的帮助部分是因为您的 Django 设置文件中有 DEBUG = True。将其更改为 False,将仅显示初始错误消息。 您可以使用 CSRF_FAILURE_VIEW 设置自定义此页面。
似乎服务器将我的代码视为攻击者。但是如何在 android 视图中添加 CSRF 模板呢?在我的应用程序中,没有表格。我很困惑。
而且,我的代码在这里:
public int login(){
try {
HttpPost httpPost = new HttpPost(loginURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", userID));
params.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
cookies = httpClient.getCookieStore().getCookies();
Log.e("Cookies", cookies.isEmpty() + "");
HttpEntity httpEntity = httpResponse.getEntity();
if(httpResponse.getStatusLine().getStatusCode() == 200){
Log.v("HTTPResponse", "200");
} else {
Log.v("HTTPResponse","" + httpResponse.getStatusLine().getStatusCode());
}
String result = EntityUtils.toString(httpEntity, "UTF-8");
} catch (MalformedURLException e){
Log.e("UserInfoCollectorMalformedURLException", e.toString());
return 0;
} catch (UnsupportedEncodingException e){
Log.e("UnsupportedIOException", e.toString());
return 5;
} catch (IOException e){
Log.e("UserInfoCollectorIOException", e.toString());
return 1;
} catch (ParseException e){
Log.e("ParseException", e.toString());
return 3;
}
Log.v("Login", "Unknown Error");
return 1000;
}
【问题讨论】:
-
在 HTTP 中使用 POST 基本上等同于发布 HTML 表单。
-
感谢大家!好像没必要开启CSRF保护。