How to handle CSRF protection in a single page application?

You can use the classic CSRF token strategies, but they can take some awkward effort to use in AJAX-based applications, and easier options are available for AJAX-specific endpoints:

  • Add an extra header to requests to your server like "X-Requested-With: XMLHttpRequest" or "X-Is-Local-XHR: true", and make your server require the header on authenticated requests. Users with old versions of Flash may be vulnerable (though old versions of Flash have had much worse vulnerabilities too, so your choice on whether this is important to you). See https://stackoverflow.com/questions/17478731/whats-the-point-of-the-x-requested-with-header

  • Verify either the Origin or Referer header is set and matches the domain in the Host header. The Origin header is sent for all POST requests by Chrome and Firefox but older browsers may not include it. The Referer header is disabled by some users for privacy reasons. The presence of either with a valid value is enough to verify the request.