REST and CSRF (Cross-Site Request Forgery)

Whether or not CSRF protection is needed is based on 2 factors: -

  1. Is the request doing a state changing action (not the same as REST API Statelessness) - State changing actions are any action that will change the state of the application.. for example delete something, add something, update something. These are actions using which the application will change the backed state of the user. All Post requests and a few Get requests will come under this category. REST APIs can have state changing actions.

  2. Is the authentication provided by browser (not limited to cookies) - CSRF happens because authentication information is included in the request by browser irrespective of whether the request was started by the user, or some other open tab. So any kind of authentication in which browser can self include information needs CSRF protection. That includes both cookie based sessions and basic authentication.

For all requests that fall in above 2 categories CSRF protection is needed.

As answered by Stephan above, Ajax requests are protected because of Same Origin Policy (SOP). SOP prevents another domain from reading the content sent by target domain. So the malicious script can't read the authorization header. But SOP doesn't prevent another domain from sending requests to the target domain. So the malicious script can still make state changing requests to the target domain. Browser will include authentication information and cookies in this request, so server needs to know whether this request originated from the malicious domain or the user. Because of this CSRF protection is needed.


Disclaimer: I am not a security expert.

Using HTTP Basic Auth does not prevent CSRF attacks via GET requests. E.g. somebody else can include an img tag in their HTML page that does a GET on some well-known URI, and your browser will happily send along the basic auth info. If the GET operation is "safe" (which is the #1 rule for anything claiming to be RESTful), this will not create a problem (beyond wasted bandwidth).

Ajax is not a problem because of the same-origin policy.

Only including a server-generated token in the HTML you generate, and validating its presence in form submission requests, will protect you from somebody else simply including a "foreign" form in their pages. You might limit this to the content types generated by browsers; no need to do so for XHR requests.