3

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).

3
  • 1
    use $http interceptor Commented Dec 9, 2014 at 6:12
  • What about just setting the same cookie the next time the tab is opened? Why is your server serving different cookies for each request? You could cycle your cookie every so often. Commented Dec 9, 2014 at 6:15
  • csrf token has to be a random value. If it's constant, then it serves no purpose. Also csrf token is sent only once. Commented Dec 9, 2014 at 6:26

2 Answers 2

5

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')
})
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I do not want to set header for every http request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.