Website Security Q&As Logo
Website Security Q&As Part of the Q&A Network
Q&A Logo

What's the best way to prevent CSRF attacks on my web application?

Asked on Oct 22, 2025

Answer

To prevent CSRF (Cross-Site Request Forgery) attacks, implement anti-CSRF tokens in your web application. These tokens ensure that requests made to your server are legitimate and originate from authenticated users.
<!-- BEGIN COPY / PASTE -->
    // Example of setting an anti-CSRF token in a form
    &lt;form method="POST" action="/submit-form"&gt;
      &lt;input type="hidden" name="csrf_token" value="your_generated_token_here"&gt;
      &lt;input type="text" name="data"&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
    <!-- END COPY / PASTE -->
Additional Comment:
  • Generate a unique CSRF token for each user session and validate it on the server side.
  • Ensure that the token is included in all state-changing requests (e.g., POST, PUT, DELETE).
  • Consider using SameSite cookies to further mitigate CSRF risks by restricting how cookies are sent with cross-site requests.

✅ Answered with Security best practices.


← Back to All Questions
The Q&A Network