Search code examples
iosangularjsdjangoionic-frameworkcsrf

ionic/angularjs with django csrf works on local server but not working on device


I am working on ionic and use Django with django-rest-framework as backend. I tried to post to my server with $http as following:

$http({
  url: url,
  method: method,
  data: {
    // some data
  }
}).success...

Also I set the following in my config:

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

I also tried ngCookies but $cookies.csrftoken does not return anything.

Here is my backend code:

class Mark(APIView):
    def post(self, request):
        # do something
        return Response({
            # something
        })

This works perfect when I used ionic local server ionic serve, but when I build it on iOS emulator or on my iPhone, csrf 403 appears:

{"detail":"CSRF Failed: CSRF token missing or incorrect."}

returned from the server.

Any idea on this? Thank you so much!


Solution

  • I do not think this information will fix your problem you will probably face it later. On iOS cookies are lost when rebooting the application, use window.localStorage to store them.

    See answer: Can you use cookies in a Cordova application?