Cross-site request forgery (CSRF)
A CSRF attack is when a valid, but unintended, request is sent to the webserver. It usually happens when users are tricked into submitting requests they didn't intend to send.
An attacker could update a user's login information or interact with the application on the user's behalf.
Forms of attack
A popular attack vector is tricking users into submitting malicious forms. The attacker can host a malicious version of a website on their private server. The site will look like the original, but the attacker controls it.
Attackers can trick users onto the malicious website with phishing emails, a link submitted by the user in user-generated content, or another way.
The attacker mirrors the attributes and fields of the original form. But since the attacker controls the form, they can manipulate values.
The request will pass authentication checks if the user is logged into the original site using a session cookie, and the session cookie hasn't been protected.
If the application has
GET endpoints that update data on the server, an attack can be performed with an image. This applies only to websites where users can submit content.
The attacker can submit an HTML image tag with the vulnerable endpoint as the source. When the user browses the application and encounters the image, the browser will send the
GET request. The request will pass authentication checks because the request is sent from the authenticated users browser.
Links are vulnerable to CSRF attacks in the same way that images are. An attacker tricks a user into clicking on a link. The link contains a URL to the vulnerable endpoint.
Mitigating and preventing attacks
Use proper HTTP methods
Make sure to use the appropriate HTTP methods on endpoints.
POST requests should create new resources.
PATCH requests should update existing resources.
Using proper 'HTTP verbs' prevents attackers from using links or images to send requests that alter data.
A CSRF token is a value that is included in the request using a hidden input field in a form.
It should be unique for the user and randomly generated so no one can guess it.
When requests are sent through a form, the server can validate that the token exists and is valid.
Session-cookies used for authentication should use the SameSite attribute. Browsers only send SameSite cookies with requests if the cookie was created on the same domain.