angularjs 如何处理 csrf?

How does angularjs handle csrf?

我在理解下面的代码时有点困难

run.$inject = ['$http'];

function run($http) {
  $http.defaults.xsrfHeaderName = 'X-CSRFToken';
  $http.defaults.xsrfCookieName = 'csrftoken';
}

因为我一直认为 csrf 被注入到 html 表单或 ajax 调用中而不是 cookie,因为 csrf 可以防止任何试图使用您的 cookie 进行身份验证的对手。

有人可以详细解释 angular 如何处理 csrf 以及它如何从后端获取令牌吗?

我无法比 angular docs 自己更好地回答这个问题,所以我只引用:

Cross Site Request Forgery (XSRF) Protection

XSRF is a technique by which an unauthorized site can gain your user's private data. Angular provides a mechanism to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an 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. The header will not be set for cross-domain requests.

To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request. On subsequent XHR 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 sent the request. The token must be unique for each user and must be verifiable by the server (to prevent the JavaScript from making up its own tokens). We recommend that the token is a digest of your site's authentication cookie with a salt for added security.

The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, or the per-request config object.

$http.defaults.xsrfCookieName 只是允许您指定 cookie 的名称,否则它将寻找默认的 XSRF-TOKEN

在服务器端实现上,我建议使用一些 node.js 中间件来处理初始 cookie 的设置,而不是自己滚动。看看 csurf in particular as it seems to be the most popular. You could also try senchalab's csrf 中间件。这些中的任何一个都应该足以让你开始。