24

I'm trying to create a POST request using angular.js to this Django view.

class PostJSON4SlickGrid(View):
    """
    REST POST Interface for SlickGrid to update workpackages
    """

    def post(self, request, root_id, wp_id, **kwargs):
        print "in PostJSON4SlickGrid"
        print request.POST
        return HttpResponse(status=200)

Therefore I created this resource.

myModule.factory('gridData', function($resource) {
    //define resource class
    var root = {{ root.pk }};
    return $resource('{% url getJSON4SlickGrid root.pk %}:wpID/', {wpID:'@id'},{
            get: {method:'GET', params:{}, isArray:true},
            update:{method:'POST'}
    });
});

Calling the get method in a controller works fine. The url gets translated to http://127.0.0.1:8000/pm/rest/tree/1/.

function gridController($scope, gridData){
    gridData.get(function(result) {
        console.log(result);
        $scope.treeData = result;
        //broadcast that asynchronous xhr call finished
        $scope.$broadcast('mySignal', {fake: 'Hello!'});  
    });
}

While I m facing issues executing the update/POST method.

item.$update();

The URL gets translated to http://127.0.0.1:8000/pm/rest/tree/1/345, which is missing a trailing slash. This can be easily circumvented when not using a trailing slash in your URL definition.

url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),

instead of

url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)/$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),

Using the workaround without the trailing slash I get now a 403 (Forbidden) status code, which is probably due to that I do not pass a CSRF token in the POST request. Therefore my question boils down to how I can pass the CSRF token into the POST request created by angular?

I know about this approach to pass the csrf token via the headers, but I m looking for a possibility to add the token to the body of the post request, as suggested here. Is it possible in angular to add data to the post request body?

As additional readings one can look at these discussions regarding resources, removed trailing slashes, and the limitations resources currently have: disc1 and disc2. In one of the discussions one of the authors recommended to currently not use resources, but use this approach instead.

Community
  • 1
  • 1
Thomas Kremmel
  • 14,575
  • 26
  • 108
  • 177

5 Answers5

40

I know this is more than 1 year old, but if someone stumbles upon the same issue, angular JS already has a CSRF cookie fetching mechanism (versions of AngularJS starting at 1.1.5), and you just have to tell angular what is the name of the cookie that django uses, and also the HTTP header that it should use to communicate with the server.

Use module configuration for that:

var app = angular.module('yourApp');
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

Now every request will have the correct django CSRF token. In my opinion this is much more correct than manually placing the token on every request, because it uses built-in systems from both frameworks (django and angularJS).

Anoyz
  • 7,431
  • 3
  • 30
  • 35
  • And you also need to make sure you wrap your view with ensure_csrf_cookie decorator: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie – Eugene Prikazchikov Jan 22 '14 at 11:25
  • Only if for some reason your view is not sending the CSRF token after you activated the CSRF middleware. – Anoyz Jan 23 '14 at 19:30
  • Thank you very much., i was banging my head from 20 hours. – Spiderman Feb 26 '15 at 10:00
  • What happens if your request is not to your backend? Will it still add the cookie to it? Isn't that a security issue? Or does it only do this if you pass relative URLs to `$http`? – Akaisteph7 Sep 01 '23 at 22:37
7

Can't you make a call like this:

$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

The data can be whatever you wish to pass and then just append &{{csrf_token}} to that.

In your resource params:{}, try adding csrfmiddlewaretoken:{{csrf_token}} inside the params

Edit:

You can pass data to the request body as

item.$update({csrfmiddlewaretoken:{{csrf_token}}})

and to headers as

var csrf = '{{ csrf_token }}'; 
update:{method:'POST', headers: {'X-CSRFToken' : csrf }} 

It is an undocumented issue

Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65
  • Thanks. I would prefer to use the resource functionality as it is working in general. I m just missing the possibiliy / syntax to add the CSFR token. – Thomas Kremmel Oct 10 '12 at 20:33
  • Edited a bit, I think the csrf should go inside your params withing the resource call. – Pratik Mandrekar Oct 10 '12 at 20:37
  • No, unfortunately no luck. I guess Django only recognizes the token when transferred via the body of the POST request. When adding it to the params I get a 403 permission denied, using this angular generated url: POST /pm/rest/tree/1/384?csrfmiddlewaretoken=FKV6x4YUurDEPerFhcGRHK1qVJwzXn HTTP/1.1" 403 – Thomas Kremmel Oct 11 '12 at 06:33
  • Yes it has to be the body, Didn't realize params referred to url params, edited my answer to show how to pass data to request body. – Pratik Mandrekar Oct 11 '12 at 06:48
  • Great, I also just discovered that you can easily set the headers as such: var csrf = '{{ csrf_token }}'; update:{method:'POST', headers: {'X-CSRFToken' : csrf }} . Do you mind to include this solution also in your answer for further reference? – Thomas Kremmel Oct 11 '12 at 07:04
  • Please note: The approach with using headers is working fine. But if you use item.$update({csrfmiddlewaretoken:{{csrf_token}}}) the token also gets appended to the URL, not as intended to the body of the request. – Thomas Kremmel Oct 11 '12 at 08:28
  • Docs say 'Calling these methods invoke an ng.$http with the specified http method, destination and parameters.' So if I really wanted to pass it in the body would use `$http.post('/someUrl', data).success(successCallback);` instead of $resource. Can't seem to find any solution otherwise, other than the headers :( – Pratik Mandrekar Oct 11 '12 at 09:14
1

In recent angularjs version giving solution is not working . So i tried the following

  • First add django tag {% csrf_token %} in the markup.

  • Add a $http inspector in your app config file

angular.module('myApp').config(function ( $httpProvider) {
   $httpProvider.interceptors.push('myHttpRequestInterceptor'); 
});
  • Then define that myHttpRequestInterceptor

angular.module("myApp").factory('myHttpRequestInterceptor', function ( ) {

   return {
             config.headers = { 
              'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() } 
             } 
   return config; 
  }}; 
});

it'll add the X-CSRFToken in all angular request

And lastly you need to add the Django middleware " django.middleware.csrf.CsrfViewMiddleware'" It'll solve the CSRF issue

0
var app = angular.module('angularFoo', ....

app.config(["$httpProvider", function(provider) {
  provider.defaults.headers.common['X-CSRFToken'] = '<<csrftoken value from template or cookie>>';
}])
Serge K.
  • 340
  • 4
  • 10
0

I use this:

In Django view:

@csrf_protect
def index(request):
    #Set cstf-token cookie for rendered template
    return render_to_response('index.html', RequestContext(request))

In App.js:

(function(A) {
    "use strict";
    A.module('DesktopApplication', 'ngCookies' ]).config(function($interpolateProvider, $resourceProvider) {
        //I use {$ and $} as Angular directives
        $interpolateProvider.startSymbol('{$');
        $interpolateProvider.endSymbol('$}');
        //Without this Django not processed urls without trailing slash
        $resourceProvider.defaults.stripTrailingSlashes = false; 
    }).run(function($http, $cookies) {
        //Set csrf-kookie for every request
        $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
        $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    });
}(this.angular));

For sending correct request you must convert object to param-form:

$http.post('/items/add/', $.param({name: 'Foo'}));//Here $ is jQuery
Dunaevsky Maxim
  • 3,062
  • 4
  • 21
  • 26