Search code examples
angularjslaravelcsrflaravel-routingcsrf-protection

Should I be using a CSRF if I'm planning on implementing a multi-app API?


I'm in the process of creating a Laravel API/AngularJS Monster. The idea of completely separating them out (Frontend, DB, API) was mainly because I wanted to get into app development and keep all things separate so the API could do all the grunt work. So in the future I intend on making interfaces of which I'll be the only one using including OS X/iOS/Native apps.

However I'm looking on stuff online and following some setups and tutorials and I'm seeing that CSRF is a good thing to implement, seems secure and the right thing to do...

But is it necessarily right for an API?

What security measures would be good for using an API?

The only thing I really know anything about implementing right now is Session cookies and using HTTPS throughout my application(s).


Solution

  • If the API is accessed client-side, then yes, you need CSRF protection.

    This assumes that cookies (or another authentication mechanism) is used from the front-end, is passed to your API from JavaScript and then actions are initiated, or content returned.

    For the items that initiate action (i.e. non safe methods - RFC 7231) you will need to send some sort of CSRF token (e.g. Synchronizer Token Pattern which is recommended, or Double Submit Cookies), although there are other valid methods for preventing CSRF such as checking for X-Requested-With or Origin headers.

    Whichever method you choose, you would be able to also implement this authentication in your apps. From a custom application retrieving the token or cookie value is trivial, or passing an extra header is easy too. What makes this CSRF protection work for your website is that the browser will restrict which other domains can read tokens or send headers because of the Same Origin Policy. If your API is on a different domain, CORS can be used to allow access from your website domain only, although it sounds like you're already past this stage. Remember to protect your API with HTTPS also, and set the Secure flag on any cookies, and you should also think about using HSTS to further secure your API and website.