Last updated: May 1, 2026
Cross-Site Request Forgery (CSRF) tricks a user’s browser into submitting authenticated actions to a trusted site. Once ubiquitous, modern browsers and frameworks have made the baseline defence far stronger. But CSRF still appears — especially in legacy APIs and apps that mishandle authentication state.
The core attack
User is logged into bank.com (browser holds session cookie). User visits malicious.com. Malicious page includes a hidden form or fetch that POSTs to bank.com/transfer?amount=1000&to=attacker. Browser automatically includes bank.com’s cookie. Transfer executes.
<!-- Malicious page -->
<form action="https://bank.com/transfer" method="POST" id="f">
<input name="amount" value="10000">
<input name="to" value="attacker">
</form>
<script>document.getElementById('f').submit();</script>
Classic CSRF. User never authorised the action, but it executes with their credentials.
SameSite cookies — the modern default defence
Cookie attribute introduced in 2016, now the baseline:
SameSite=Strict— cookie never sent on cross-site requests. Tightest, sometimes breaks OAuth flows.SameSite=Lax— cookie sent on top-level navigations (links), but not on cross-site POSTs or iframes. Modern default since Chrome 80.SameSite=None— cookie sent on cross-site requests. RequiresSecure. Used for third-party contexts (single sign-on, embeds).
Most auth cookies should be SameSite=Lax; Secure; HttpOnly. Use Strict when no third-party navigation is expected.
Anti-CSRF tokens
Before SameSite, the standard defence. Server generates a random token per session; includes in forms; validates on submission.
<!-- Form with CSRF token -->
<form action="/transfer" method="POST">
<input type="hidden" name="_csrf" value="a1b2c3d4e5f6...">
<input name="amount">
<input name="to">
<button>Submit</button>
</form>
Server compares form’s _csrf token against session-stored token. Attacker’s malicious form can’t include the right token. Most frameworks provide this automatically (Django, Laravel, Rails, Express with csurf).
Double-submit cookie pattern
Alternative: CSRF token stored as cookie; same value included in request header or body; server verifies they match. No server-side state needed. Popular in SPAs consuming REST APIs.
Custom request headers + CORS
For JSON APIs, a simple defence: require a custom header (e.g. X-Requested-With: XMLHttpRequest). Browsers only allow custom headers on same-origin requests or via CORS preflight — preflight fails without server approval. Many JSON APIs use this as their sole CSRF defence.
What still breaks
- Legacy APIs accepting POST without token or SameSite-aware cookies
- GET endpoints performing state changes — SameSite=Lax still sends cookie on GET navigations; CSRF via
<img src=bank.com/transfer?...>still works - Same-site sub-domain attacks — if attacker controls xss.yourdomain.com, they’re same-site relative to www.yourdomain.com; SameSite doesn’t protect
- Wrong SameSite configuration — SameSite=None without Secure fails; SameSite unset behaves differently across browsers
GET vs POST — the under-appreciated rule
GET requests should never have side effects. Logging out via GET (/logout), deleting via GET (/delete/123), modifying via GET is a security failure for multiple reasons — CSRF, caching, logging. Use POST/PUT/DELETE with appropriate semantics.
Testing for CSRF
- Identify state-changing endpoints
- Check if request works WITHOUT CSRF token
- Check if request works with REMOVED CSRF token
- Check if request works with BLANK CSRF token
- Check if CSRF token is session-bound (not replayable across users)
- Check SameSite cookie attribute on auth cookies
- Check CORS headers — overly-permissive Access-Control-Allow-Origin defeats same-origin CSRF defences
Defences stack
- SameSite=Lax or Strict on auth cookies
- Anti-CSRF tokens for form-based apps
- Custom headers + CORS policy for JSON APIs
- Don’t use GET for state-changing actions
- Implement Referer/Origin header checks as belt-and-braces
Quick reference summary
- CSRF = forcing authenticated browser to submit unwanted action
- Modern default: SameSite=Lax cookies significantly reduce attack surface
- Framework-generated CSRF tokens are the primary defence for forms
- JSON APIs: custom headers + strict CORS
- GET requests must be safe (no side effects)
- OWASP Top 10 dropped CSRF (2017) because framework defaults improved — but not solved
Module Quiz · 20 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
CSRF in 2026 — SameSite default and what it changed
Chrome and other modern browsers default cookies to SameSite=Lax. Cross-site POSTs no longer carry the cookie automatically — most classic CSRF is dead by browser default. What still works:
SameSite=Lax as default for session cookies; SameSite=Strict for highest-trust cookies (forces re-login on cross-site nav).X-Requested-With) — CORS preflight blocks cross-origin script from sending custom headers without explicit allow.Operational hardening + detection
SameSite=Lax; Secure; HttpOnly.SameSite=Strict or step-up MFA.CSRF in single-page applications — the SameSite false-comfort
SPAs often think they are CSRF-immune because they use JWT in headers. The catch: many SPAs still use cookies for refresh tokens. The refresh endpoint becomes a CSRF target — attacker can trigger refresh from another origin, getting a new access token issued (which they cannot read but the server may log + tie to anomaly events). More serious: SPAs that use session cookies for first-party API calls revert to classic CSRF risk. Defence patterns:
X-CSRF-Token) that cross-origin script cannot send without CORS preflight.CSRF in mobile / native clients — the changed threat model
Native mobile apps do not run third-party HTML, so classical browser-driven CSRF does not apply. The CSRF surface in mobile is different:
android:exported="false" unless explicitly required. For Indian banking / UPI apps: deep-link CSRF has caused real account-takeover incidents; mandate explicit confirmation before any state-changing deep-link action.CSRF attacks against authentication endpoints
CSRF on login is a subtle attack: attacker logs the victim into the attacker’s account; victim then performs actions thinking they are in their own account; attacker harvests the data created. The reverse — login CSRF — is what enables further phishing.
Defencesame as other CSRF-protected endpoints — token, SameSite, Origin validation.
Logout CSRFforces victim logout; nuisance, sometimes leveraged in phishing chains.
Password-change CSRFmost damaging; the attacker takes over the account. Always require current-password on password-change forms regardless of CSRF token; the layered defence prevents CSRF + token-leak compounding.
Account-deletion CSRFirreversible; requires re-auth.
For Indian banking appsevery state-changing endpoint requires a CSRF defence; payment endpoints additionally require explicit re-auth (PIN / biometric / OTP). The layered defence reflects the irreversibility of financial transactions.
Performance discipline that strengthens security
A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.
Observability that catches attacks alongside outages
Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.
DPDP and sectoral obligations a practitioner cannot ignore
Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.
A small threat-modelling routine before every release
A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.
Further reading
Additional FAQs
Do JWTs prevent CSRF?
If sent in a header (Authorization: Bearer), yes — the browser does not auto-attach it. If stored in a cookie, no — same CSRF risk as session cookies. The cookie pattern is XSS-safer; the header pattern is CSRF-safer; pick by threat model.
Is CSRF still relevant in 2026?
Less than 2018 thanks to SameSite defaults. Still relevant for legacy apps, sub-domain takeover scenarios, and any app that cannot rely on SameSite (some federated SSO flows). Token-based defence remains a free belt-and-suspenders.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.