Search code examples
securityasp.net-web-apicsrf-protection

How do you prevent CSRF attacks from clients without cookies in ASP.NET Web API?


I'm making an ASP.NET Web API 2 service as a RESTful API to support mobile applications.

The problem is all the articles on the web on CSRF including:

All speak about cookie-based anti-CSRF validation.

I need to put such a cookie in my mobile application, and not only that, it has to come pre-loaded for the application to immediately work. Is there a way to put in such anti-CSRF security methods without having to set cookies? Or is there maybe a way to pre-load a security cookie in a mobile application so we can immediately use it without a cookie setting step?


Solution

  • Answer: You shouldn't need to.

    You will need to protect your Web API with some sort of authentication mechanism (presumably), and I recommend only making your API available over HTTPS. Implementing HSTS is also recommended.

    A CSRF attack can only happen when cookies are shared on the client. By that I mean that the client has access to cookies from multiple domains (such as a web browser storing cookies for each site you visit). However, a web application API client typically only contacts a single domain (that of your API). Any cross site attack cannot use cookies within your API as the client is not shared (HTTP client in web application is separate than HTTP client in the mobile browser - or should be). Therefore your web application API should already be safe against CSRF if the API is for your mobile application only.

    Note, as per Jaxidian's comment, the above is assuming that cookies are used as the session management mechanism rather than an HTTP orientated one (e.g. basic auth, NTLM or Kerberos).