2014-05-15 2 views
1

내가하지만, 내 tastypie 자원에 대한 아약스 요청을 사용하고 난 SessionAuthentication()하고, 항상 401장고 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 
얻을 수 DjangoAuthorization()를 사용하는 경우에도

이것은 캘린더 리소스이므로 이벤트 모델이 있고 내 ajax 요청은 django-admin에로드 된 javascript 파일에 있습니다. 또한 요청 헤더에 csrf 토큰 및 세션 ID가 있는지 확인했지만 작동하지 않습니다.

.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 토큰 헤더를 (당신이 그것을 검사 볼 수 있지만, 그것은 당신의 코드에 나타나지 않습니다) 제공하지 않았습니다.

$.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 데이터로 토큰을 전달해야합니다 :

은 자바 스크립트가 포함 된 페이지의 어딘가에 {% csrf_token %} 태그를 포함, 다음 beforeSend 옵션을 사용하여 X-CSRF-Token 헤더를 설정하기 위해 AJAX 방식을 수정 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