Django的REST框架 - 与PUT请求验证错误(Django rest framework -

2019-07-31 11:23发布

我有一个非常简单的资源像这样我的模式“PRESENTACION”

class PresentacionResource(ModelResource):
    model = Presentacion
    fields = (some fields)
    ignore_fields = (few to ignore)

我需要实现这种验证,所以只要我阅读,我创建了两个包装

class AuthListOrCreateModelView(ListOrCreateModelView):
    permissions = (IsAuthenticated, )
class AuthInstanceModelView(InstanceModelView):
    permissions = (IsAuthenticated, )

然后我在我的urls.py

url(r'^presentaciones/$', AuthListOrCreateModelView.as_view(resource=PresentacionResource), name='presentacion-root'),
url(r'^presentaciones/(?P<id>[0-9]+)$', AuthInstanceModelView.as_view(resource=PresentacionResource), name='presentacion'),

这是get做工精细“presentaciones /的要求,但是当我尝试做一个PUT请求,我越来越不允许的403

什么是奇怪,我是GET是工作的罚款:只要我登录,它的正确响应,但如果我退出它与403 FORBIDDEN响应。

Answer 1:

如果您正在使用Django的基于会话的认证,那么你可能会绊倒建成的Django的CSRF保护(见UserLoggedInAuthentication类[1])。

如果是这样的话,你需要确保CSRF的cookie被发送到客户端,然后你可以适应jQuery的指令[2]与可能更改数据请求发送X-CSRFToken头。

[1] http://django-rest-framework.org/_modules/authentication.html

[2] https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax



Answer 2:

如果问题是X-CSRF令牌头可以修改Backbone.sync这样发送令牌,每个POST,PUT,DELETE请求。

        /* alias away the sync method */
        Backbone._sync = Backbone.sync;

        /* define a new sync method */
        Backbone.sync = function(method, model, options) {

            /* only need a token for non-get requests */
            if (method == 'create' || method == 'update' || method == 'delete') {
                // CSRF token value is in an embedded meta tag 
                var csrfToken = $("meta[name='csrf_token']").attr('content');

                options.beforeSend = function(xhr){
                    xhr.setRequestHeader('X-CSRFToken', csrfToken);
                };
            }

            /* proxy the call to the old sync method */
            return Backbone._sync(method, model, options);
        };


Answer 3:

我意识到这是一个较旧的职位,但最近我处理这个问题。 扩大对@ orangewarp的回答,并使用Django文档( https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax ),这里有一个解决方案:

该解决方案采用了csrftoken饼干。 另一种解决方案是创建你的API在CSRF令牌端点,并从那里抢CSRF。

  Backbone._sync = Backbone.sync;

  Backbone.sync = function(method, model, options) {
      //from django docs
      function getCookie(name) {
          var cookieValue = null;
          if (document.cookie && document.cookie != '') {
              var cookies = document.cookie.split(';');
              for (var i = 0; i < cookies.length; i++) {
                  var cookie = jQuery.trim(cookies[i]);
                  // Does this cookie string begin with the name we want?
                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                      break;
                  }
              }
          }
          return cookieValue;
      }

      /* only need a token for non-get requests */
      if (method == 'create' || method == 'update' || method == 'delete') {
          var csrfToken = getCookie('csrftoken');

          options.beforeSend = function(xhr){
              xhr.setRequestHeader('X-CSRFToken', csrfToken);
          };
      }

      return Backbone._sync(method, model, options);
  };


文章来源: Django rest framework - Authentication error with PUT requests