I noticed tokens used in form submissions to prevent CSRF attacks, though in 2016 a lot of people are moving to JS frontend & restful API backends. I'm puzzled, with this approach is there no need for CSRF tokens anymore?

I think CSRF is an issue on form submissions since all the session data is sent with every request. But is AJAX different? I.e. all cookies (session data) are not sent?

You can assume my API is protected by CORS (over TLS), i.e. Access-Control-Allow-Origin is set only for the site I expect data to be collected from.

So what I am asking is: Is CORS & an AJAX API call the way to avoid generating tokens in my front end code?

1 Answer 1


IIUC only Ajax calls can set custom headers, and those are domain-restricted.

Btw CORS is not a type of protection, it is there to allow less protection (ie. let you make requests between domains)

So simply adding X-CSRF-CHECK: 1 onto your application's AJAX calls and having your backend such as PHP check for $_SERVER['HTTP_X_CSRF_CHECK'], you don't have to generate random tokens to prevent CSRF attacks since other Websites cannot set those headers. This is great since your forms can be easier cached now.

An attacker who can craft a header, will not have your session data since they won't be in your browser session with the server.

A CSRF attacker who cannot craft a header, though can use your session data will fail the X_CSRF_CHECK' header on your backend.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .