Cross-site request forgery
Cross-site request forgery, also known as CSRF or XSRF, is a attack in which an alternate website sends fake requests to a real website.
The attack usually works like this:
- A user is logged into
shopping.com
, an online store where he shops regularly.shopping.com
leaves a session id in a cookie so the user doesn't need to login every visit.
- The user is sent a email linking to
attacker-website.com
. They visit this website. - The JS code in
attacker-website.com
sends a POST request toshopping.com
to order an item.- This request will carry the session id which is already authenticated.
- Without CSRF protection, the order will go through.
To protect against CSRF, the website shopping.com
should do the following:
- While the user is browsing
shopping.com
, it backend sets a CORS cookie using an HTTP header in a response.My-Xsrf-Cookie:UKL7smHAK4xENQj5pYbi
- 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.
My-Xsrf-Header:UKL7smHAK4xENQj5pYbi
- Before processing the order, the backend will check the Xsrf header to make sure that it matches what was sent originally.
This works for the following reasons:
- When sending the XSRF token, the backend sends it in an HTTP header telling the browser to stores it as a cookie,
- If other websites make a request (via fetch or XmlHTTPRequest) to get an XSRF token, the token will be sent in the HTTP header.
- By default, the browser will only let the other website see a few whitelisted HTTP headers due to same-origin policy so they will not see the XSRF token.
- If other websites make a request (via fetch or XmlHTTPRequest) to get an XSRF token, the token will be sent in the HTTP header.
- Next the browser stores the cookie under
shopping.com
.- Due to same-origin policy, other websites cannot see the cookies for
shopping.com
.
- Due to same-origin policy, other websites cannot see the cookies for