Search code examples
apisecuritycsrfcsrf-protection

API CSRF protection


I have an app that consists of simple JSON API and React frontend. Authentication is handled via cookies and frontend is served from the same domain I use for API. Since I don't allow CORS, wonder if API is going to be protected against CSRF attacks if it accepts only requests with some custom header, for example if X-Requested-With is set to XMLHttpRequest?


Solution

  • An attacker can send a cross-site request with an XMLHttpRequest without violation the Same-Origin Policy (SOP) - the only limit here is that the attacker's site won't be able to see the response. Cookies are included with every request sent by the victim's browser so the API call will still fire with a cross-site XHR, so this API is still vulnerable to CSRF.

    If you don't want to make any security architecture changes, then the CSRF Prevention Cheat Sheet recommends checking the Origin header. This document describes other methods, such as the CSRF token synchronizer method which could be used as a header element and is considered a stronger method of defense.