Junior Superman
Junior Superman

Reputation: 151

AngularJS - Setting default http headers dynamically

To overcome csrf attack, I have to send in csrf-token value in a header for every request by picking in the value from cookie as described here. Since this is to be done at every request, I am setting the default headers for $http in the main module's run function.

Now, If a new tab is opened for the same website, a new csrf token (in cookie) is issued by the server. Since the run function is run only once, the default header for csrf will be old one (for old tab), while the new csrf cookie will be sent to server, resulting in csrf-mismatch.

How to overcome this at a global level?

I want somehow to create a function which will be run everytime the $http is called, so that then I'll override the default headers.

Note: I do not want to set this header value for every $http request.

(Not that I think that it's relevant, but I'm using ui-router)

Edit

This is not just limited to csrf-token, I want to set some other headers too based on the logged in user, which has to be done dynamically (say when one user logs in, and logs out, then another user logs in).

Upvotes: 3

Views: 4724

Answers (2)

fliedonion
fliedonion

Reputation: 952

How about headers $http(config) parameter.

$scope.getWithHeader = function(){
    $http({
        method: 'GET',
        url: 'http://fiddle.jshell.net',
        headers: {
          'CustomHeader': 'HelloWorld'
        }
    }).success(function(){
        console.log("success");
    });
};

sample code on jsFiddle

enter image description here

Upvotes: 1

harishr
harishr

Reputation: 18055

you need to use http interceptor to do this on every request. read more about http interceptors here

below is one such example

module.factory('xsrfTokenInterceptor', function ($q, $http) {
    return {
        'response': function (response) {
            var cookies = response.headers("Set-Cookie");
            var token = someCrazyParsing(cookies);
            $http.defaults.headers.common["X-CSRFToken"]=token;
            return response || $q.when(response);
        }  
    };
});
module.config(function($httpProvider){
    $httpProvider.interceptors.push('xsrfTokenInterceptor')
})

Upvotes: 5

Related Questions