2
votes

I got a CSRF failure when connecting django server using POST method in an android app. The httpResponse saying as below:

Forbidden (403)
CSRF verification failed. Request aborted.

Reason given for failure:

CSRF cookie not set.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function uses RequestContext for the template, instead of Context. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting.

It seems the server treats my code as an attacker. But how to add a CSRF template in an android view? In my app, there is no form. I am confused.

And, my code is here:

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;
}
1
Using POST in HTTP is basically equivalent of posting an HTML form.Lmickos
Thank all of U! Seems it is not necessary to turn on CSRF protection.ZhangLei

1 Answers

2
votes

If you have access to the server code, you could remove your CSRF protection on you API views using the csrf_exempt decorator. See this answer for more details Do CSRF attacks apply to API's?