2014-05-15 51 views
1

我使用Ajax請求我tastypie資源,但即使我用SessionAuthentication()和DjangoAuthorization(),它會永遠401Django的Tastypie總是返回401未經授權

resources.py

class EventsResource(ModelResource): 

user = fields.ForeignKey(UserResource, 'user') 

    class Meta: 
     queryset = Event.objects.all() 
     resource_name = 'events' 
     filtering = {'start': ALL, 
        'end':ALL 
        } 
     list_allowed_methods = ['get', 'post','put', 'patch'] 
     detail_allowed_methods = ['get', 'post', 'put', 'delete'] 
     authentication = SessionAuthentication() 
     authorization = Authorization() 
     include_resource_uri = True 
     limit = 0 
     always_return_data = True 

這是一個日曆的資源,所以我有一個事件模型,並且我的ajax請求在django-admin中加載的javascript文件中;我還檢查了請求標頭是否有csrf標記和會話標識,但不起作用。

.ajax({ 
        url: event.resource_uri, 
        dataType: 'json', 
        contentType: 'application/json; encode=UTF-8', 
        type: 'DELETE', 
        success: function() { 
         $calendar.fullCalendar('removeEvents'); 
         $calendar.fullCalendar('refetchEvents'); 
         $('#modal-confirm').modal('hide'); 
         showmsg('Evento eliminato correttamente', 'warning'); 
        } 
       }); 

回答

1

您正在使用SessionAuthentication但尚未提供CSRF令牌頭(我看你檢查它,但它不會出現在你的代碼)。

附上{% csrf_token %}標籤某處頁面包含你的JavaScript,然後修改您的AJAX方法使用beforeSend選項來設置X-CSRF-Token標題:

$.ajax({ 
    url: event.resource_uri, 
    dataType: 'json', 
    contentType: 'application/json; encode=UTF-8', 
    type: 'DELETE', 
    beforeSend: function(jqXHR) { 
     jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val()); 
    }, 
    success: function() { 
     $calendar.fullCalendar('removeEvents'); 
     $calendar.fullCalendar('refetchEvents'); 
     $('#modal-confirm').modal('hide'); 
     showmsg('Evento eliminato correttamente', 'warning'); 
    } 
}); 
0

您應該通過CSRF令牌與每個POST數據POST請求。在CSRF令牌的建議來源是餅乾,像這樣:

getCookie: function(name) { 
    var cookieValue = null; 
    if (document.cookie && document.cookie != '') { 
     var cookies = document.cookie.split(';'); 
     for (var i = 0; i < cookies.length; i++) { 
      var cookie = $.trim(cookies[i]); 
      if (cookie.substring(0, name.length + 1) == (name + '=')) { 
       cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
       break; 
      } 
     } 
    } 
    return cookieValue; 
} 

然後,你會設置頁眉上的AJAX請求是這樣的:

var csrftoken = this.getCookie('csrftoken'); 
//Use Setup prior or use the beforeSend on the fly 
/*$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    } 
});*/ 
$.ajax({ 
    type: "POST", 
    dataType: "json", 
    contentType: "application/json", 
    url: "/my/uri/", 
    data: {"any": "thing"}, 
    beforeSend: function(xhr, settings) { 
     xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    }, 
    success: function(data) { 
     console.log("Weeey") ; 
    } 
}); 

參考:https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax

相關問題