403 on DELETE to an endpoint with good credentials from an Angular client

1,538 views
Skip to first unread message

Rodrigo Gadea

unread,
Nov 7, 2013, 1:01:22 AM11/7/13
to django-res...@googlegroups.com
Hi guys!

Does anyone have a clue about why doing a DELETE request from an AngularJS client to an /api/model/<pk>/ gives a 403 error but the "web interface" does it successfully?

When DELETEing from Angular, it gives the error of "bad csrf token", but the token is the same that the button in the web/html interface. The same Angular client can do POSTs and other stuff (it is authenticated) with the same credentials, but fails there and I can't think why (it's probably something silly).

Thanks in advance,
Rodrigo

Yarin Miran

unread,
Feb 3, 2014, 7:40:18 AM2/3/14
to django-res...@googlegroups.com
Hi Rodrigo, did you find the solution to this? I'm experiencing the same issues as well.

Yarin.

Tom Christie

unread,
Feb 3, 2014, 8:30:50 AM2/3/14
to django-res...@googlegroups.com
I guess it's probably because you need to be adding the CSRF token as a request `X-CSRFToken` header.
It's a little different in the browsable API, because it's actually making a `POST` request with the `_method=DELETE` style method overloading, so the CSRF token can simply be included as a regular POST field, rather than as an HTTP header.

Rodrigo Gadea

unread,
Feb 3, 2014, 4:48:08 PM2/3/14
to django-res...@googlegroups.com
Yarin & Tom,

I'm asking the frontend part of my team to see if this issue was resolved, because the header was there, and I couldn't find a reason on the backend, and I never heard of it anymore, so it may be on the AngularJS side... but it is weird...


--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Howie Weiner

unread,
Mar 14, 2014, 6:50:51 AM3/14/14
to django-res...@googlegroups.com
I just ran into this problem. Tom is spot on. Angular is failing as there is no CSRF token

For other HTTP Method, this can be sorted by overriding the HTTP default headers as follows:

$httpProvider.defaults.headers.post['X-CSRF-Token'] = csrfToken
$httpProvider.defaults.headers.put['X-CSRF-Token'] = csrfToken
$httpProvider.defaults.headers.patch['X-CSRF-Token'] = csrfToken

However, Angular doesn't seem to allow:

$httpProvider.defaults.headers.delete['X-CSRF-Token'] = csrfToken

So, based on Tom's suggestion, I added the extra header to my resource as follows:


coreServices.factory('Activity', ['djResource', function(djResource) {
    return djResource('/api/activities/:id/', {id: '@id'}, {
        update: {method: 'PUT'},
        delete: {method: 'POST', headers: {'X-HTTP-Method-Override': 'PATCH'}}
    });
}]);

Hope that helps
Reply all
Reply to author
Forward
0 new messages