角JS验证令牌CSRF在POST请求 [英] Angular JS Verify CSRF Token in POST Request

查看:259
本文介绍了角JS验证令牌CSRF在POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using AngularJS with Rails. I have the following request which updates users in bulk.

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

这不可能是一个GET请求由于URL的长度(http://support.microsoft.com/kb/208427)

This cannot be a 'GET' request due to restrictions in the length of the URL (http://support.microsoft.com/kb/208427)

但对于POST的要求,我们需要在头一个CSRF真实性令牌。

But for 'POST' request, we need to have a CSRF authenticity token in the header.

我们怎样才能设置CSRF令牌到后请求头?

How can we set the CSRF Token to the post request header?

推荐答案

您可以设置HTTP头作为 $解释HTTP 服务。

You can set http headers as explained in the $http service.

您可以在全局设置它:

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

或单个请求:

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

下面是一个重要的报价:

Here is an important quote from Angular:

跨站请求伪造(XSRF)保护XSRF是一种技术
  其中未经授权的网站可以获取用户的私人数据。角
  提供以下机制来对抗XSRF。当执行XHR
  请求,$ http服务从一个名为cookie的读取令牌
  XSRF-TOKEN并将其设置为HTTP标头的X XSRF-TOKEN。由于只有
  JavaScript的在您的域中运行可以读取cookie,你的服务器
  可以放心的XHR从JavaScript来运行你的
  域。

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.

要充分利用这一点,你的服务器需要设置一个令牌
  JavaScript的叫XSRF-TOKEN第一次HTTP GET可读的会话cookie
  请求。在随后的非GET请求的服务器可以验证该
  饼干匹配的X XSRF-TOKEN HTTP头,因此可以肯定的说
  只有JavaScript在域上运行都能读取的标记。该
  令牌必须为每个用户唯一的,必须是可核查
  服务器(以prevent中的JavaScript制作了自己的令牌)。我们
  建议令牌是您网站的身份验证摘要
  饼干盐以增加安全性。

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.

这篇关于角JS验证令牌CSRF在POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆