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
<form method="POST" action="/submit-form">
<input type="hidden" name="csrf_token" value="your_generated_token_here">
<input type="text" name="data">
<button type="submit">Submit</button>
</form>
<!-- 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.
Recommended Links: