angular, django and csrf

前端 未结 3 1323
太阳男子
太阳男子 2020-12-13 10:59

from http://docs.angularjs.org/api/ng.$http , it says we should set default headers to include the token, so i am following it.

my code goes something like this

相关标签:
3条回答
  • 2020-12-13 11:26

    If you use AngularJS 1.1.3 or newer you can use xsrfHeaderName and xsrfCookieName:

    var myapp = angular.module('myapp', ['ngCookies', 'ui.bootstrap']).
      config(['$routeProvider', function($routeProvider, $httpProvider, $cookies){
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        ...
    

    See $location in 1.1.3 the documentation.

    0 讨论(0)
  • 2020-12-13 11:30

    You can only use the $httpProvider in the config-method. But the problem is that you cannot use $cookies in the config-method. There only $cookiesProvider is supported. That is described (a bit) in the Module Loading & Dependencies section.

    What you can do is set the headers at runtime as suggested in the angularjs.org docs

    So to make your example work, you can do the following:

    var myapp = angular.module('myapp', ['ngCookies', 'ui.bootstrap']).
        config(['$routeProvider', function($routeProvider){
            $routeProvider.
                when('/', {
                    templateUrl: '/partials/home.html',
                    controller: HomeCtrl
                }).
                when('/game/:gameId/shortlist/create',{
                    templateUrl: '/partials/create-shortlist.html',
                    controller: CreateShortlistCtrl
                }).
                otherwise({redirectTo: '/'});
        }]);
    
    myapp.run(function($rootScope, $http, $cookies){
        // set the CSRF token here
        $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
    
        $http.get('/api/get-current-user').success(function(data){
            $rootScope.current_user = data;
            $rootScope.current_team = $rootScope.current_user.team;
        });
        $http.get('/api/get-current-season').success(function(data){
            $rootScope.current_season = data;
        });
    });
    

    And don't forget to include the angular-cookies.js file in your html-file!

    0 讨论(0)
  • 2020-12-13 11:40

    Here is a small lib that could make this more simple https://github.com/pasupulaphani/angular-csrf-cross-domain

    0 讨论(0)
提交回复
热议问题