How will you prevent CSRF attacks in a web application?
To prevent CSRF attacks in a web application, implement anti-CSRF tokens. These are unique, random values associated with a user’s session and included within forms or AJAX requests. They’re validated server-side before processing the request. If they don’t match, it’s likely a forged request.
Another method is SameSite Cookies which restricts cookies to first-party contexts, preventing them from being sent on cross-origin requests. This can be set to ‘Strict’ or ‘Lax’, depending on your needs.
Content Security Policy (CSP) can also help by limiting where resources can be loaded from, reducing the risk of attack if an attacker can inject HTML into your site.
Lastly, ensure that GET requests are safe and idempotent as per HTTP specification. This means they do not change any state on the server side. POST should be used for any state-changing operations.