Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework, ajax POST works but PATCH throws CSRF Failed: CSRF token missing or incorrect

I am porting my project to Django Rest Framework to make a proper REST Api for my project, I think it helps a lot designing the API and making it robust but I am running into a problem :

I have a entry model and associated ListCreateAPIView and RetrieveUpdateDestroyAPIView views. I can successfully post a new entry instance in the list through an ajax request and providing the csrfmiddlewaretoken as I would do in regular Django View.

    POST entries/

Now I am trying to apply a patch to an existing instance using the same csrfmiddlewaretoken like so:

    PATCH entries/3

The response status code is then 403 FORBIDDEN vith error CSRF Failed: CSRF token missing or incorrect although I checked in firebux that csrfmiddlewaretoken is in the request data.

I don't what is wrong and I cannot find out where in the code is the request rejected.

Note: I can patch the object with the Django Rest Framework browsable api.

I hope someone can help. Thanks. Olivier

EDIT

I was digging into the code to see where the rejetion of the PATCH request occurs and I found in django.middleware.csrt.py the following:

        if csrf_token is None: #<--- csrf_token is defined
            # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
            # and in this way we can avoid all CSRF attacks, including login
            # CSRF.
            return self._reject(request, REASON_NO_CSRF_COOKIE)

        # Check non-cookie token for match.
        request_csrf_token = ""
        if request.method == "POST": #<--- This fails but request_csrf_token is in request.DATA
            request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')

        if request_csrf_token == "":
            # Fall back to X-CSRFToken, to make things easier for AJAX,
            # and possible for PUT/DELETE.
            request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

The second test fails because it is not a POST request but the information required is in request.DATA. So it seems that django is not keen to accept PATCH request. What do you think would be the best way to go around this?

Would you recommend using a different authentication system (there are some in Django-rest-framework documentation)?

EDIT2

I found out a solution: I observed that the browsable api is actually sending a POST request but with a parameter _method="PATCH", so I did the same with my ajax request and it works fine.

I don't know if it is the right way to do, any feedback and opinion is welcome!

EDIT3

So, after more reading, I discovered (I already kind of knew..) that because some browsers do not support requests like PUT, PATCH, DELETE, the way to go is to send a post request with X-HTTP-Method-Override in the header.

So the good way to go I think is to do the following:

$.ajax({
   headers: {
    'X-HTTP-Method-Override': 'PATCH'
   },
   type : "POST",
   ...
});
like image 975
overlii Avatar asked Apr 02 '14 13:04

overlii


2 Answers

I also meet the same question, I learn from @overlii solution problem method. I use django rest framework web interface to do put/patch, and I find the HTTP Request Headers Info like below: HTTP Request Headers

From this image, we can find X-CSRFTOKEN header, so I set ajax header info like below:

$.ajax({
        headers: {
            'X-CSRFTOKEN': '{{ csrf_token }}'
        },
        type: "PATCH",
        dataType: "json",
        url: "/api/path/",
        data: "",
        success: function(data){
                
        }
});

I use this way to send patch request and find this can run rightly!

like image 156
David_li Avatar answered Nov 17 '22 00:11

David_li


I finally add this as an answer.

So, after more reading, I discovered (I already kind of knew..) that because some browsers do not support requests like PUT, PATCH, DELETE, the way to go is to send a post request with X-HTTP-Method-Override in the header.

So the good way to go I think is to do the following:

$.ajax({
    headers: {
        'X-HTTP-Method-Override': 'PATCH'
    },
    type : "POST",
...
});
like image 28
overlii Avatar answered Nov 17 '22 00:11

overlii