AngularJS - dynamically configure default HTTP headers
To overcome the csrf attack, I have to send the csrf-token value in the header for each request, fetching the value from the cookie as described here . Since this needs to be done on every request, I set the default headers for $ http in the main module's startup function.
Now if a new tab is opened for the same website, a new csrf server (in cookie) is served by the server. Since the launch function only runs once, the default header for the csrf will be the old one (for the old tab), while the new csrf cookie will be sent to the server, resulting in a csrf mismatch.
How to overcome this globally?
I want to somehow create a function that will run every time $ http is called, so I override the default headers.
Note. I don't want to set this header value for every $ http request.
(Not that I think this is relevant, but I am using ui-router)
Edit
This is not limited to just the csrf token, I want to also set some other headers based on the logged in user to be executed dynamically (say when one user logs in and out and then other user logs in).
source to share
you need to use a http interceptor for this on every request. Learn more about http interceptors here
Below is an examplemodule.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')
})
source to share
How about headers $http(config)
.
$scope.getWithHeader = function(){
$http({
method: 'GET',
url: 'http://fiddle.jshell.net',
headers: {
'CustomHeader': 'HelloWorld'
}
}).success(function(){
console.log("success");
});
};
example code on jsFiddle
source to share