Lesson 5 of 11
Cross-Site Request Forgery (CSRF)
CSRF tricks authenticated users into unknowingly submitting malicious requests. Since browsers automatically include cookies with every request, an attacker's page can forge authenticated requests to a victim's bank, email, or any logged-in application.
How CSRF Works
# Attack Scenario: CSRF bank transfer attack
# 1. Victim is logged into bank.com (has valid session cookie)
# 2. Victim visits attacker's malicious page (evil.com)
# 3. evil.com contains this hidden HTML:
<form id="transfer" action="https://bank.com/transfer" method="POST">
<input type="hidden" name="to_account" value="ATTACKER_ACCOUNT">
<input type="hidden" name="amount" value="5000">
</form>
<script>document.getElementById('transfer').submit();</script>
# 4. Browser submits the form to bank.com
# 5. Browser AUTOMATICALLY includes the session cookie for bank.com
# (Per browser's same-site-unaware cookie policy)
# 6. bank.com sees: valid session + valid POST → processes transfer
# Why this works:
# Bank.com cannot distinguish legitimate request from forged one
# Both have the same session cookie - that's all bank.com checks
# The request originates from the victim's browser - same IP, same user
# What CSRF can do: Change password, change email, make purchases,
# transfer money, delete account, post content as victimCSRF Token Defense
# Defense: Anti-CSRF tokens (synchronizer token pattern)
# Server generates a unique, unpredictable token per session/form
# Token is embedded in the form and validated on POST
# Attacker cannot forge the request because they don't know the token
# (SOP prevents evil.com from reading bank.com's response to get the token)
# Flask-WTF CSRF protection (automatic for all forms)
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.secret_key = os.urandom(32)
csrf = CSRFProtect(app)
# In your HTML template (Jinja2):
# <form method="POST">
# {{ form.hidden_tag() }} ← Inserts CSRF token automatically
# ...
# </form>
# For AJAX requests, send token in header:
# JavaScript:
# fetch('/api/transfer', {
# method: 'POST',
# headers: { 'X-CSRFToken': document.cookie.match(/csrftoken=([w-]+)/)[1] },
# body: JSON.stringify({amount: 100})
# })
# Django: CSRF middleware enabled by default
# Spring Security: CSRF protection enabled by default
# Rails: protect_from_forgery enabled by default
# SameSite Cookie Attribute - Modern Defense
# Set-Cookie: session=abc123; SameSite=Strict
# SameSite=Strict: Cookie NEVER sent on cross-site requests (breaks some flows)
# SameSite=Lax: Cookie not sent on cross-site POST (allows GET navigation)
# SameSite=None; Secure: Sent everywhere (old behavior - for legitimate cross-site auth)Common Mistakes
- Using GET requests for state-changing operations - GET requests are always vulnerable to CSRF via <img src>, <link href>, etc.; state changes must use POST/PUT/DELETE
- Storing CSRF token in a cookie and validating it from the same cookie - attackers can set cookies via XSS; the token must be in a hidden form field or header AND in a cookie (double-submit pattern requires both to match)
- Implementing CSRF protection but exempting API endpoints - SPAs and mobile apps use APIs; API endpoints need CSRF protection too (Origin header validation or CSRF tokens)
Tip
Tip
Practice CrossSite Request Forgery CSRF in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of CrossSite Request Forgery CSRF from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with CrossSite Request Forgery CSRF is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- CSRF tricks authenticated users into unknowingly submitting malicious requests.
- Using GET requests for state-changing operations - GET requests are always vulnerable to CSRF via <img src>, <link href>, etc.; state changes must use POST/PUT/DELETE
- Storing CSRF token in a cookie and validating it from the same cookie - attackers can set cookies via XSS; the token must be in a hidden form field or header AND in a cookie (double-submit pattern requires both to match)
- Implementing CSRF protection but exempting API endpoints - SPAs and mobile apps use APIs; API endpoints need CSRF protection too (Origin header validation or CSRF tokens)
Finished this lesson?