AngularJS - 动态设置默认的http标头

时间:2014-12-09 05:55:09

标签: angularjs

为了克服csrf攻击,我必须在每个请求的标头中发送csrf-token值,方法是按照here所述从cookie中选择值。由于这是在每次请求时完成的,我在主模块的运行功能中设置$ http的默认标题。

现在,如果为同一网站打开了新标签,则服务器会发出新的csrf标记(在cookie中)。由于run函数只运行一次,因此csrf的默认标头将为旧标签(对于旧标签),而新的csrf cookie将发送到服务器,导致csrf-mismatch。

如何在全球范围内克服这个问题?

我想以某种方式创建一个函数,该函数将在每次调用$ http时运行,这样我就会覆盖默认的头文件。

注意:我不想为每个$ http请求设置此标头值。

(不是我认为它是相关的,但我使用的是ui-router)

修改

这不仅限于csrf-token,我想根据登录用户设置一些其他标头,这必须动态完成(比如当一个用户登录,然后注销,然后另一个用户登录)在)。

2 个答案:

答案 0 :(得分:5)

你需要使用http拦截器在每个请求上执行此操作。在此处详细了解http interceptors

下面是一个这样的例子

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')
})

答案 1 :(得分:1)

标题$http(config)参数怎么样。

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

jsFiddle

上的示例代码

enter image description here

相关问题