Middle
How is CSRF attack prevented? How did you protect against it in your project?
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.
To prevent CSRF, the following are usually used:
- CSRF tokens: the server generates a unique token for each session or form, which the client must send with each request. The server checks the token and rejects requests without a valid token.
- Checking the Origin or Referer header: the server verifies that the request came from a trusted domain.
- Using SameSite cookies: setting the
SameSiteflag on cookies restricts cookies to be sent only with requests from the same site.
In my project, we used CSRF tokens embedded in the framework (for example, Django or Spring Security). The token was automatically inserted into forms and checked on the server. Also, for CORS APIs, we configured headers and used SameSite=Lax for cookies to minimize the risk.