Cross Site Request Forgery (XSRF) Protection AngularJS

时间:2017-11-13 06:11:48

标签: asp.net angularjs security cors csrf

Our AngularJS app is located in site.com and our api is hosted in api.site.com, The backend is written by ASP.NET Web API, It is appearent that the CORS should be enabled between site.com and api.site.com, the documentation in here says:

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.

I have bolded the last line what doc says, is enabling CSRF protection for my application useless in this scenario? or is my app immune from this kind of attacks?

1 个答案:

答案 0 :(得分:2)

回答你的问题:

  

在这种情况下,为我的应用程序启用CSRF保护是否无效?

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

  

我的应用程序是否可以免受此类攻击?

没有。事实上,AngularJS使用cookie-to-header预防方法,如果你不小心的话,这并不是完全可靠的!有关详情,请访问here

总而言之,文档只是告诉您为您处理客户端实现。您需要执行以下操作:

  • 创建CSRF令牌(确保它是随机的,无法猜到)&在登录期间将其与用户会话相关联
  • 断言所有对API的传入请求都有X-XSRF-TOKEN标头,并且标头的值是与用户会话关联的标记

是的,请确保启用同源政策