Sobes.tech
Middle

What is CSRF and how to fight it?

sobes.tech AI

Answer from AI

CSRF (Cross-Site Request Forgery) is an attack where an attacker tricks a user into performing an unwanted action on a website where they are authenticated.

How to prevent CSRF:

  • Use CSRF tokens: when loading a form, the server generates a unique token that the client must send back. The server checks the token before performing the action.
  • Check the Origin or Referer header: ensure the request comes from a trusted domain.
  • Use SameSite cookies: setting the cookie with the SameSite flag restricts cookies to be sent only with requests from the same site.

Example of using a CSRF token in a form:

<form method="POST" action="/submit">
  <input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
  <!-- other fields -->
  <button type="submit">Submit</button>
</form>

On the server, it is checked that csrf_token matches the expected value.

What is CSRF and how to fight it? — Frontend - sobes.tech