Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS-动态设置默认http头_Angularjs - Fatal编程技术网

AngularJS-动态设置默认http头

AngularJS-动态设置默认http头,angularjs,Angularjs,为了克服csrf攻击,我必须通过从cookie中选取值,在每个请求的报头中发送csrf令牌值,如上所述。因为这是在每次请求时都要完成的,所以我在主模块的run函数中设置$http的默认头 现在,如果为同一网站打开了一个新选项卡,则服务器将发出一个新的csrf令牌(cookie中)。由于run函数只运行一次,csrf的默认标头将是旧标头(对于旧选项卡),而新的csrf cookie将发送到服务器,从而导致csrf不匹配 如何在全球范围内克服这一问题 我想创建一个函数,它将在每次调用$http时运行

为了克服csrf攻击,我必须通过从cookie中选取值,在每个请求的报头中发送csrf令牌值,如上所述。因为这是在每次请求时都要完成的,所以我在主模块的run函数中设置$http的默认头

现在,如果为同一网站打开了一个新选项卡,则服务器将发出一个新的csrf令牌(cookie中)。由于run函数只运行一次,csrf的默认标头将是旧标头(对于旧选项卡),而新的csrf cookie将发送到服务器,从而导致csrf不匹配

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

我想创建一个函数,它将在每次调用$http时运行,这样我就可以覆盖默认的头

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

(我并不认为这是相关的,但我正在使用ui路由器)

编辑


这不仅限于csrf令牌,我还想根据登录用户设置一些其他头,这必须动态完成(例如,当一个用户登录并注销时,然后另一个用户登录)。

您需要使用http侦听器对每个请求执行此操作。阅读更多关于这里的信息

下面就是这样一个例子

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')
})
headers参数怎么样

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


使用$http拦截器下次打开选项卡时设置相同的cookie怎么样?为什么您的服务器为每个请求提供不同的cookie?您可以每隔一段时间循环一次cookie。csrf令牌必须是随机值。如果它是常数,那么它就没有作用。而且csrf令牌只发送一次。我不想为每个http请求设置头。