Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular, django and csrf

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

var myapp = angular.module('myapp', ['ngCookies', 'ui.bootstrap']).
    config(['$routeProvider', function($routeProvider, $httpProvider, $cookies){
        $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, $httpProvider){
    $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;
    });
    $rootScope.csrf_token = $cookies.csrftoken;
    console.log($httpProvider.defaults.headers.common);
    //$httpProvider.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});

as you can see, i have applied multiple approaches but am unable to set header with csrf token. the two errors i have encountered are

Uncaught Error: Unknown provider: $httpProviderProvider <- $httpProvider

what am i doing wrong?

like image 830
Yousuf Jawwad Avatar asked May 21 '13 06:05

Yousuf Jawwad


People also ask

How does Django handle CSRF?

Django protects against CSRF attacks by generating a CSRF token in the server, send it to the client side, and mandating the client to send the token back in the request header. The server will then verify if the token from client is the same as the one generated previously; if not it will not authorise the request.

Is CSRF token necessary Django?

Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

What is CSRF in angular?

CSRF is one such attack that will exploit the user's security by sending an unwanted request to the server that is beneficial to the attacker. CSRF attacks are relevant only in cookie-based session handling because the attacker exploits the session's ID stored in cookies to perform tasks that require session tokens.

What is CSRF Django?

The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.


2 Answers

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.

like image 176
Reto Aebersold Avatar answered Sep 25 '22 07:09

Reto Aebersold


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!

like image 24
DanEEStar Avatar answered Sep 22 '22 07:09

DanEEStar