在Android

时间:2018-09-29 10:03:58

标签: android django

在下面的代码段中运行时,我在Django服务器上收到CSRF令牌不匹配错误。 有人可以帮我在这里找到问题吗。

try{
    loginUrl = new URL(urls[0]);
    loginUrlConnection = (HttpURLConnection) loginUrl.openConnection();
    loginUrlConnection.setRequestMethod("GET");
    String userPass = "aniket" + ":" + "rinku123";
    String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);
    loginUrlConnection.setRequestProperty("Authorization", basicAuth);
    loginUrlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    loginUrlConnection.setRequestProperty("X-CSRF-TOKEN", "fetch");
    loginUrlConnection.getContent();

    if (HttpURLConnection.HTTP_OK == loginUrlConnection.getResponseCode()) {
                cookie = loginUrlConnection.getHeaderField("Set-Cookie");
                String[] parts = cookie.split("\\=|\\;");       // split response by " and find the string that's 64 characters (csrf token)
                for(String s: parts) {
                    if(s.length() == 64) {
                        xcsrfToken = s;
                        break;
                    }
                }
            }

     loginUrl = new URL(urls[0]);
     loginUrlConnection = (HttpURLConnection) loginUrl.openConnection();
     loginUrlConnection.setRequestMethod("POST");
     userPass = "aniket" + ":" + "rinku123";
     basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);
     loginUrlConnection.setRequestProperty("Authorization", basicAuth);
     loginUrlConnection.setRequestProperty("cookie", cookie);
     loginUrlConnection.setRequestProperty("X-CSRF-TOKEN", xcsrfToken);
     loginUrlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
     loginUrlConnection.setConnectTimeout(10000);
     loginUrlConnection.setDoInput(true);
     loginUrlConnection.setDoOutput(true);
     loginUrlConnection.setUseCaches(true);
     loginUrlConnection.connect();
  

错误::禁止(CSRF令牌丢失或不正确。):/ accounts / login /

1 个答案:

答案 0 :(得分:0)

在您的视图上使用from django.views.decorators.csrf import csrf_exempt

您可以像这样使用它作为装饰器

@csrf_exempt 类Myview(View):    template_name ='1.html'