Last Updated: September 09, 2019
·
1.167K
· imran-aspire

Django CSRF Token issue in Angularjs

  • 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'); });
    </code>

  • Then define that myHttpRequestInterceptor
    angular.module("myApp").factory('myHttpRequestInterceptor', function ( ) { return { config.headers = { 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() } } return config; } }; });

</code>

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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

Angular apps often share the page with analytics and payment scripts that are not Angular modules. Those scripts execute on the same origin as the framework.

Security insights from Cside