angularjs - Angular JS 在 POST 请求中验证 CSRF token

标签 angularjs javascript-framework

我正在使用 AngularJS 和 Rails。我有以下批量更新用户的请求。

 $http{
    method: 'POST',
    url: $scope.update_url,
    params: {selected_ids: userIds}
 }

由于 URL 长度限制,这不能是“GET”请求 (http://support.microsoft.com/kb/208427)

但是对于“POST”请求,我们需要在 header 中包含 CSRF 真实性 token 。

我们如何将 CSRF token 设置为 post 请求 header ?

最佳答案

您可以按照 $http 中的说明设置 http header 。服务。

您可以进行全局设置:

$httpProvider.defaults.headers.post['My-Header']='value'   (or)
$http.defaults.headers.post['My-Header']='value';

或者对于单个请求:

$http({
   headers: {
      'My-Header': 'value'
   }  
});

这是 Angular 的重要引述:

Cross Site Request Forgery (XSRF) Protection XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides following mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie called XSRF-TOKEN and sets it as the HTTP header X-XSRF-TOKEN. Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on first HTTP GET request. On subsequent non-GET requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that only JavaScript running on your domain could have read the token. The token must be unique for each user and must be verifiable by the server (to prevent the JavaScript making up its own tokens). We recommend that the token is a digest of your site's authentication cookie with salt for added security.

关于angularjs - Angular JS 在 POST 请求中验证 CSRF token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109927/

相关文章:

javascript - 尝试使用 Lodash 返回深层嵌套对象

javascript - Phonegap 错误 - Android 上未定义的 "Cannot read property ' 捕获

javascript - 比较 YUI 和 Ext JS

c# - 如何使用 jquery 获取或设置单选按钮列表的选定索引?

javascript - 如何防止 knockout.js 数据绑定(bind)中的字符转义?

backbone.js - Backbone 代码产生不可用的堆栈跟踪

javascript - Ui-router父状态,子状态 Controller

angularjs - 单击选项卡菜单时如何在 ionic 框架中停止视频(html5 视频)

javascript - 如何调用 Angular Controller ?

javascript - BigNumber 与 Webpack + Angular 的使用