Cross-site request forgery: Difference between revisions

 
(2 intermediate revisions by the same user not shown)
Line 13: Line 13:
==Defense==
==Defense==
To protect against CSRF, the website <code>shopping.com</code> should do the following:
To protect against CSRF, the website <code>shopping.com</code> should do the following:
# While the user is browsing <code>shopping.com</code>, it backend sets a CORS cookie using an HTTP header in a response.
# While the user is browsing <code>shopping.com</code>, the backend sets a CORS cookie using an HTTP header in a response.
#: <code>My-Xsrf-Cookie:UKL7smHAK4xENQj5pYbi</code>
#: <code>XSRF-TOKEN:UKL7smHAK4xENQj5pYbi</code>
#* This cookie will be different for each session.
#* This cookie will be different for each session.
# When making requests to checkout, the front-end will add the XSRF token to the HTTP request as a header or hidden form field.
# When making requests to checkout, the front-end will add the XSRF token to the HTTP request as a header or hidden form field.
#: <code>My-Xsrf-Header:UKL7smHAK4xENQj5pYbi</code>
#: <code>X-XSRF-TOKEN:UKL7smHAK4xENQj5pYbi</code>
# Before processing the order, the backend will check the XSRF header to make sure that it matches what was sent originally.
# Before processing the order, the backend will check the XSRF header to make sure that it matches what was sent originally.
#* I.e. it checks that the (XSRF header or hidden field) matches the (sent cookie or save session token).
#* I.e. it checks that the (XSRF header or hidden field) matches the (sent cookie or save session token).
;Notes
* Typically, the server will update the CSRF cookie every request.
* If using a header, the defense is call ''cookie-to-header''.
* Using a hidden form field is called ''double submit cookie'' and does not require JavaScript.


===Defense Explanation===
===Defense Explanation===
Line 29: Line 34:
#* Due to same-origin policy, other websites cannot see the cookies for <code>shopping.com</code>.
#* Due to same-origin policy, other websites cannot see the cookies for <code>shopping.com</code>.


Note that other origins can read hidden form fields and can send custom headers.   
Note that other origins may be able to read hidden form fields and can send custom headers if <code>Access-Control-Allow-Origin</code> is set incorrectly.   
This it is important for the backend to check the XSRF key against one that other websites cannot read.
It is important for the backend to check the XSRF key against one that other websites cannot read.


If you send the XSRF token in a cookie and a hidden form field, this will not require any JS since the browser will automatically repeat the hidden form field.   
If you send the XSRF token in a cookie and a hidden form field, this will not require any JS since the browser will automatically repeat the hidden form field.