在 Android 应用程序中使用 POST 方法连接 django 服务器时,出现 CSRF 失败。 httpResponse 如下:
Forbidden (403)
CSRF verification failed. Request aborted.
失败原因:
CSRF cookie not set.
一般来说,当存在真正的跨站请求伪造时,或者当 Django 的 CSRF 机制没有被正确使用时,就会发生这种情况。对于 POST 表单,您需要确保: 您的浏览器正在接受 cookie。 View 函数使用 RequestContext 作为模板,而不是 Context。 在模板中,每个针对内部 URL 的 POST 表单内都有一个 {% csrf_token %} 模板标记。 如果您不使用 CsrfViewMiddleware,则必须在使用 csrf_token 模板标记的任何 View 以及接受 POST 数据的 View 上使用 csrf_protect。 您看到此页面的帮助部分是因为您的 Django 设置文件中有 DEBUG = True。将其更改为 False,则仅显示初始错误消息。 您可以使用 CSRF_FAILURE_VIEW 设置自定义此页面。
服务器似乎将我的代码视为攻击者。但是如何在android View 中添加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;
}
最佳答案
如果您有权访问服务器代码,则可以使用csrf_exempt删除API View 上的CSRF保护。装饰师。 有关更多详细信息,请参阅此答案 Do CSRF attacks apply to API's?
关于android - 如何使用android避免CSRF失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351518/