Search code examples
pythondjangoangularjscsrfdjango-csrf

Django and Angular POST request - CSRF failed


I have deployed an API with Django REST API Framework in local. My mobile application is developed with Ionic framework (with AngularJS).

In my app, when I want to request (POST method) in Ajax, I have this error:

CSRF Failed: CSRF token missing or incorrect.

I have not received this error when I requested in the Django REST API integrated project.

I researched for solutions on the web, but none of it worked.

Project Information :

Django file settings.py:

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'klipix.django-crossdomainxhr-middleware.OrganizationMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

I used the TokenAuthentication method (http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication). My django-crossdomainxhr-middleware.py file:

class OrganizationMiddleware(object):

def process_view(self, request, view_func, view_args, view_kwargs):
header_token = request.META.get('HTTP_AUTHORIZATION', None)
if header_token is not None:
  try:
    token = sub('Token ', '', request.META.get('HTTP_AUTHORIZATION', None))
    token_obj = Token.objects.get(key = token)
    request.user = token_obj.user
  except Token.DoesNotExist:
    pass

In my app I tried to add this solution but it did not work :

angular.module('starter', ['ionic'])
.run(function($rootScope, $ionicPlatform, $http) {

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

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

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

Kindly provide valuable inputs for this.


Solution

  • For me this works with angular 1.4:

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