7

I'm working on a PHP website based entirely on AJAX (via jQuery). It's a single page in which all requests are made by AJAX.

Related to the protection against CSRF I have encountered the problem of having to manually include the token on every request I make, which is extremely tedious and uncomfortable. Looking for an alternative solution to tokens, I read about SOP (Same Origin Policy) in relation to AJAX requests. If I understood it well, xmlhttprequest is not allowed across different domains (unless this enabled CORS, which is not the case).

So, in this case, I'm wondering if checking the origin of the request (through HTTP_ORIGIN) and the header X-Requested-With (to ensure the request is an AJAX request), would be enough in order to prevent CSRF attacks. i.e, I wanted to know if there is any token really needed considering the above conditions.

Thanks so much for your time.

  • AJAX requests are allowed across different domains. On the other hand,responses to that AJAX requests may not make it to the requester depending on your CORS configuration. For example lets say attacker tries to steal user info from the victims who visit attacker's site. If victims have your site open in the next tab(authenticated), then attacker will be able to make AJAX request to your server. But,since your server's response headers don't contain access-control-allow-origin * and access-control-allow-credentials true, browser of the victim won't return the response to the attacker. – LazyHands Dec 12 '15 at 7:16
  • I understand what you mean but sounds really unsafe. if the attacker is able to send an AJAX request, probably he/she doesn't need to get a response from the server. The real damage is that he/she will be able to send the request; so, where's the protection of SOP with this? I don't see any chance of security... – cooper Dec 14 '15 at 9:07
  • How can be adding a header to every request tedious? Just don't copypasta everything. Not only that there are things like beforeSend, you can always write a tiny method or two adding the header and delegating to whatever does the whole work ($.get, $.put). – maaartinus May 16 '16 at 1:25
7

Yes, you can use a custom header such as X-Requested-With to protect AJAX requests from CSRF.

A customer header is not allowed cross-domain without CORS being enabled on your server. The Origin header could also be used, however the logic for this is not straightforward.

If you wanted to add extra security to the custom header in the spirit of defence in depth, you could add a token to the header. However, as you are saying this is the tedium you want to avoid, checking a custom header would be enough bar any future vulnerabilities in browser plugins like Flash or Silverlight that enable this header to be set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.