CSRF Attacks
How a Cross-Site Request Forgery Attack Works
Cross-site request forgery, or CSRF, is an attack that tricks a logged-in user's browser into sending a request to a website the user already trusts. The request performs an action, such as changing an email address or a password, without the user intending it.
Browsers automatically attach a site's cookies to requests sent to that site, even when the request starts on a different page. Cookies are small pieces of data that keep a user signed in, so the target site sees a request that appears to come from the logged-in user. The attacker never reads the response and never sees the cookie. They only cause the request to be sent. CSRF is often confused with cross-site scripting, which is a different attack.
Consider a site owner who is signed in to a hosting control panel and then opens a page controlled by an attacker. The page quietly submits a form to the control panel. If the panel does not check where the request came from, it may accept the change as genuine.
How Sites Prevent CSRF Attacks
Several controls work together to stop forged requests:
- Anti-CSRF tokens are unpredictable values tied to a user's session. The server includes them in its forms and checks them on every change. A forged request from another site cannot include the correct value, because the attacker's page cannot read it.
- SameSite cookies are a cookie setting that tells the browser when to send cookies on cross-site requests. Modern browsers treat cookies without a setting as Lax, which blocks many forged requests. Strict is stricter still.
- Correct request methods keep actions that change data off GET requests, because a GET request can be triggered by a simple link or image. Changes should use POST requests, which can be protected with tokens.
Some protections sit at the level of the page rather than the request. For example, clickjacking uses hidden frames instead, and is limited by settings described in HTTP security headers.
Frequently asked questions
Can CSRF steal my password or data?
Usually not directly. Browsers block the attacker's page from reading responses from another site, so the attacker cannot see the data. CSRF instead makes the browser perform actions. Changing an email address or password can still lead to account takeover, which is why the attack matters even though the attacker cannot see the data.
Do APIs need CSRF protection?
It depends on how they sign users in. APIs that rely on cookies sent automatically by the browser can be exposed to CSRF. APIs that expect an authorisation token, which the application's own code adds to each request, are generally not exposed in the same way, because the browser does not attach that token on its own.