What is CSRF?
CSRF stands for Cross Site Request Forgery. Let us say you are on your Bank Web Site, logged on and paying your bills. While the session is activity, your 5th Grader interrupts you with a Math question. Of course you need to google the answer as you have long forgotten 5th Grade Math Mr. Andy Ruport taught you. You end up on a site that is infected with Malware while you are still logged on to your Bank’s website. The malware on the site could issue a state changing operation such as Fund Transfer on your behalf to your Bank’s website. Since you are already logged on to your Bank Website, there is an active session cookie that get sent on the request to your Bank’s site. So, unbeknownst to you a Fund Transfer request to your Bank on your behalf. This in a nut shell is CSRF Attack.
Refer to the CSRF documentation on OWASP Website for additional information.
The defense for CSRF Attack in a traditional web application is to expect a CSRF Token on every state changing request that the server validates with the token saved in the Session. Since APIs are supposed to be stateless, there is no CSRF Token that can be maintained across requests in REST API calls. Refer to the CSRF Prevention sheet sheet on OWASP website for additional details. CSRF Guard is a widely used library to implement CSRF Defense in traditional web applications.
The CSRF Defense in REST APIs is to expect a custom header such as X-XSRF-TOKEN by the API. By making the client set a custom header in the request, the attacker can not rely upon traditional CSRF Attach such as auto-submit of a HTML Form as the attacker can not set custom headers via that attack vector. If the attacker were to rely up on sending an AJAX request using XMLHttpRequest (Level 2) than the CORS protection mechanism supported by all modern browsers would kick in and allow the REST API to accept or deny the request from the attacker controlled site.
This is a simple and elegant CSRF Defense that can be implemented for stateless REST APIs.