Android client login to Django server, how to pass crsf: |

I am creating an Android Client application to connect to a Django server. The problem here is that I cannot log in to my server :( what's wrong, help me: | Here is my loginFunction ():

  • Create DefaultHttpClient:

    DefaultHttpClient httpClientStatic = new DefaultHttpClient();
    
  • Function to get crsf from server:

    public String getCsrfFromUrl(String url) {
        HttpGet httpGet = new HttpGet(url);
    
        HttpResponse httpResponse = httpClientStatic.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        List<Cookie> cookies = httpClientStatic.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.e("COOKIES GET ",  "Empty Cookies");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                Log.e("COOKIES GET ",  cookies.get(i).getName()+"--"+cookies.get(i).getValue());
            }
        }
        return cookies.get(0).getValue();
    }
    
  • Function for sending username, transfer, crsf to server:

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
    
        // Making HTTP GET request to get csrfmiddlewaretoken:
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            Log.e("JSON", "In login user 02.4");
            HttpResponse httpResponse = httpClientStatic.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            .....
            //Next is read respone, and return json type
        }
    
  • Input function:

    public JSONObject loginUser(String username, String password){
        // Building Parameters
    
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(loginURL);
        params.add(new BasicNameValuePair("csrfmiddlewaretoken", csrfmiddlewaretoken));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        return json;
    }
    

It still returns error 401 anh 500 status: |.

+3
source share

All Articles