CSRF (Cross-Site Request Forgery) exploit việc browser tự động gửi cookies khi request đến domain — attacker tạo form/image trên evil.com gửi request đến bank.com, browser tự động attach session cookie của user.
Ví dụ: <img src='https://bank.com/transfer?to=attacker&amount=1000'> — nếu user đang logged in và bank không có CSRF protection, transfer xảy ra.
CSRF (Cross-Site Request Forgery) exploits the fact that browsers automatically send cookies with requests to a domain — an attacker creates a form or image on evil.com that sends a request to bank.com, and the browser automatically attaches the user's session cookie.
- Example: <img src='https://bank.com/transfer?to=attacker&amount=1000'> — if the user is logged in and the bank has no CSRF protection, the transfer executes.
- Prevention: SameSite cookie attribute is the primary defense today — SameSite=Strict: cookie is not sent in any cross-site request (including link navigation); SameSite=Lax (Chrome default): cookie is sent on top-level GET navigation but not in POST/iframe/img — sufficient for most cases; SameSite=None: requires Secure, sent in all cross-site requests.
- CSRF tokens: a random token stored in the session, included in a hidden form field and verified server-side — attackers cannot read the token due to the same-origin policy.
- Double Submit Cookie: send the token in both a cookie and the request body/header — the server verifies they match; no server-side state required.
- Custom request headers (AJAX): XMLHttpRequest and fetch cannot set custom headers cross-origin without a CORS preflight — adding X-Requested-With: XMLHttpRequest or Content-Type: application/json naturally prevents CSRF because attackers cannot create cross-origin requests with custom headers.
- Origin header checking: verify the Origin/Referer header matches the expected domain — not sufficient on its own as it can be spoofed in some cases.