Search code examples
asp.netangularjssecuritycross-domaincsrf

Cross Site Request Forgery (XSRF) Protection AngularJS


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?


Solution

  • In response to your questions:

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

    No. The documentation simply tells you that AngularJS helps make the implementation of CSRF protection easier for you, and you are responsible for completing the implementation with the help of AngularJS's XSRF feature.

    Is my app immune from this kind of attacks?

    No. In fact, AngularJS uses the cookie-to-header prevention approach, that is not completely fool proof if you are not careful! For more information, please visit here.

    To summarise, the documentation simply tells you that the client-side implementation is handled for you. You will need do the following part:

    • Create CSRF token (make sure it's random and can't be guessed) & associate it with user session during login
    • Assert that all incoming requests to your API have the X-XSRF-TOKEN header, and that the value of the header is the token that is associated with the user’s session

    and yes, please make sure you enable your same-origin policy.