跨站请求伪造 (XSRF) 防护 AngularJS

Cross Site Request Forgery (XSRF) Protection AngularJS

我们的 AngularJS 应用程序位于 site.com,我们的 api 托管在 api.site.com,后端由 ASP.NET Web [=24] 编写=],似乎应该在 site.comapi.site.com 之间启用 CORS,here 中的文档说:

XSRF is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website. AngularJS 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.

我已将文档所说的最后一行加粗,在这种情况下为我的应用程序启用 CSRF 保护是否无用?还是我的应用程序可以免受此类攻击?

回答您的问题:

Is enabling CSRF protection for my application useless in this scenario?

没有。该文档只是告诉您 AngularJS 有助于您更轻松地实施 CSRF 保护,您有责任在 AngularJS 的 XSRF 功能的帮助下完成实施。

Is my app immune from this kind of attacks?

没有。其实AngularJS就是采用了cookie-to-header的预防方式,一不小心就不是万无一失的!欲了解更多信息,请访问 here.

总而言之,文档只是告诉您 client-side 实现已为您处理。您将需要执行以下部分:

  • 创建 CSRF 令牌(确保它是随机的并且不能被猜到)并在登录期间将其与用户 session 相关联
  • 断言对您 API 的所有传入请求都具有 X-XSRF-TOKEN header,并且 header 的值是与用户的session

是的,请确保启用您的 same-origin 政策