Sobes.tech
Junior

What is CSRF?

sobes.tech AI

Answer from AI

CSRF (Cross-Site Request Forgery) is a type of attack where an attacker tricks a user into performing unwanted actions on a website where the user is already authenticated.

The essence of the attack is that a malicious site or email contains a request that the user's browser automatically sends to the target site. If the user is logged in to the target site, their browser will send cookies, and the request will be executed with their rights.

For example, this could be a request to change a password, transfer money, or delete an account.

Various methods are used to protect against CSRF:

  • CSRF tokens: Secret, unique tokens for each request, generated on the server and sent with each form or AJAX request. The server verifies the token's validity.
  • SameSite cookie attribute: Sets a rule that cookies are only sent by the browser when requests originate from the same domain where the cookie was set.
  • Checking Origin and Referer headers: The server checks where the request came from. However, these headers can be altered by an attacker or may not be present in some cases.
  • Re-authentication for critical actions: Requesting password re-entry before performing important operations.

The most effective and common method is the use of CSRF tokens.

// Example of adding a CSRF token to a form
<form action="/transfer" method="POST">
  <input type="hidden" name="_csrf_token" value="server_generated_token">
  <input type="number" name="amount">
  <button type="submit">Transfer</button>
</form>
// Example of CSRF token verification on the server (Node.js with Express)
app.post('/transfer', csrfProtection, (req, res) => {
  // Handle the request after successful token verification
});