I've been doing my own CSRF protection using PHP. From what I've read I decided to use a cookie to implement my protection but feel a little confused as to whether my method is secure against CSRF attacks.
So my method follows:
User sends request to login
Server checks if a CSRF token is set, if not create one and store it in their Session and create a Cookie with the token as well
Validate the CSRF token through checking if it is in the POST request, if not then check for the token in $_COOKIE
Send message back if token is invalid...
I decided to use a cookie to store the token as this will work for Ajax requests and I won't have to include it every time I use an Ajax POST.
What I am confused about is couldn't an attacker just make a request; POST or GET and because the cookie is there it just gets sent with the request anyway, thus being a valid request as the token is sent with the browser every time?
XMLHttpRequest
uses CORS. But a hidden<form>
that is submitted using JavaScript, can still send a POST request to a foreign domain. And such request will include all cookies of the user. Storing a CSRF in a Cookie is as if you don't have a CSRF token. – t.niese[...]Simple cross-origin requests generated outside this specification (such as cross-origin form submissions using GET or POST or cross-origin GET requests resulting from script elements) typically include user credentials, so resources conforming to this specification must always be prepared to expect simple cross-origin requests with credentials.[...]
(4 Security Considerations) – t.niese