Skip to content
Back to Blog
·9 min read·technology

CSRF Attack Prevention: How Cross-Site Request Forgery Works

Learn how CSRF exploits authenticated sessions, how it differs from XSS, and the anti-CSRF token and SameSite cookie controls Indian developers must implement.

BR

Bachao.AI Research Team

Cybersecurity Research

Scan Your Attack Surface

Security exposure this creates

Unpatched vulnerabilities in your tech stack are the #1 entry point for breaches targeting Indian businesses. Here's what to watch.

Cross-Site Request Forgery (CSRF) is a web attack where an authenticated user's browser is tricked into sending unauthorized requests to a trusted application — without the user's knowledge. Unlike XSS, which injects malicious scripts into a page, CSRF exploits the trust a server places in a user's browser session. A single successful CSRF attack can trigger fund transfers, change account settings, or escalate privileges — all using the victim's own authenticated session. This guide explains how CSRF works, how it differs from XSS, and the prevention controls that every Indian developer should implement today.

73%Indian SMBs with no formal security audit in the last 12 months (DSCI 2025)
ℹ️
NOTE
CSRF was ranked in the OWASP Top 10 for multiple consecutive editions before being merged into broader access-control categories in 2021 — reflecting how widespread the vulnerability class remains in production web applications.

What Is CSRF and How Does It Differ from XSS?

CSRF and Cross-Site Scripting (XSS) are both browser-level attacks, but they exploit different trust relationships.

XSS attacks the user's trust in the application — malicious script is injected into a page and runs in the victim's browser, stealing cookies, tokens, or session data.

CSRF attacks the application's trust in the user's browser — the attacker crafts a forged request that the victim's authenticated browser sends on the attacker's behalf. The application sees a valid session cookie and honors the request.

AttributeXSSCSRF
Exploit targetUser's trust in the siteServer's trust in the browser
Attack vectorInjected script in the pageForged HTTP request from another origin
Session required on victimNoYes — victim must be logged in
Visible to victimSometimesAlmost never
ImpactData theft, session hijackUnauthorized state-changing actions
Primary defenseContent Security Policy, output encodingAnti-CSRF tokens, SameSite cookies
The key distinction: XSS reads data from the victim's session; CSRF performs actions using it.

How a CSRF Attack Works: Step by Step

graph TD A[Victim logs in to bank.example.in] --> B[Server issues session cookie] B --> C[Victim visits attacker controlled page] C --> D[Malicious page auto-submits hidden form] D --> E[Browser attaches session cookie automatically] E --> F[Bank server receives forged transfer request] F --> G{CSRF token present?} G -->|No token - VULNERABLE| H[Transfer executes as victim] G -->|Token validated - SAFE| I[Request rejected 403] style A fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style B fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style C fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style D fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style E fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style F fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style G fill:#1e3a5f,stroke:#3B82F6,color:#e2e8f0 style H fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0 style I fill:#1e3d2f,stroke:#10B981,color:#e2e8f0

The attack works because browsers automatically send cookies for a domain with every request to that domain — regardless of which page originated the request. The server cannot distinguish a genuine user action from a forged one unless additional verification is in place.

A classic attack scenario in the Indian fintech context:

  1. A user logs into their net-banking portal. The server sets a session cookie.
  2. Without logging out, the user opens a phishing email and clicks a link to attacker.example.com.
  3. That page contains a hidden HTML form pointing to bank.example.in/transfer with pre-filled amount and beneficiary.
  4. JavaScript auto-submits the form. The browser dutifully appends the session cookie.
  5. The bank server receives a fully authenticated-looking request and processes the transfer.
The victim sees nothing. The damage is done.
🚨
DANGER
CSRF attacks require the victim to be actively logged in. Attackers time their delivery — phishing emails sent during business hours, malicious ads on news sites visited at lunch — to maximize the chance the target has an active session.

Real-World Impact

CSRF is not theoretical. The OWASP Top 10 has listed it as a critical vulnerability category across multiple editions, and it appears consistently in penetration test findings for Indian banking, e-commerce, and government portals.

Common high-impact CSRF scenarios:

    1. Fund transfers — Trigger a payment or NEFT/IMPS transfer to an attacker-controlled account.
    2. Email or mobile number change — Lock the user out of account recovery.
    3. Password reset initiation — Chain with CSRF to take over an account.
    4. Admin privilege escalation — On internal tools, force an admin to grant attacker roles.
    5. Data deletion — DELETE endpoints without CSRF protection allow mass data wipes.
    6. OAuth token grant — Force a user to authorize a malicious third-party application.
⚠️
WARNING
Any HTTP endpoint that performs a state-changing operation (POST, PUT, PATCH, DELETE) and relies solely on session cookies for authentication is potentially vulnerable to CSRF. This includes REST APIs consumed by browser clients — not just traditional HTML form submissions.

Know your vulnerabilities before attackers do

Run a free VAPT scan — takes 5 minutes, no signup required.

Book Your Free Scan

Vulnerable vs. Fixed Code Examples

Vulnerable: No CSRF Protection (Node.js / Express)

javascript
// VULNERABLE — no CSRF token check
app.post('/api/transfer', requireAuth, async (req, res) => {
  const { toAccount, amount } = req.body;
  await transferFunds(req.user.id, toAccount, amount);
  res.json({ success: true });
});

Any authenticated user's browser can be made to hit this endpoint from a third-party page.

Fixed: CSRF Token Validation (Node.js / Express + csurf pattern)

javascript
// Note: the 'csurf' npm package was deprecated in 2023.
// Use csrf-csrf, lusca, or your framework's built-in CSRF middleware instead.
// The synchronizer-token pattern below is framework-agnostic.

// Generate and bind token to session
app.get('/transfer-form', (req, res) => {
  const csrfToken = req.session.csrfToken || crypto.randomBytes(32).toString('hex');
  req.session.csrfToken = csrfToken;
  res.render('transfer', { csrfToken });
});

// Validate token on state-changing request
app.post('/api/transfer', requireAuth, async (req, res) => {
  const tokenFromRequest = req.body._csrf || req.headers['x-csrf-token'];
  if (!req.session.csrfToken || !timingSafeEqual(req.session.csrfToken, tokenFromRequest)) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }
  const { toAccount, amount } = req.body;
  await transferFunds(req.user.id, toAccount, amount);
  res.json({ success: true });
});

The CSRF token is unique per session and per form render. An attacker on a different origin cannot read it (same-origin policy blocks cross-origin reads), so they cannot forge a valid request.

javascript
// Set session cookie with SameSite=Strict or Lax
res.cookie('session', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'Strict',  // or 'Lax' for broader compatibility
});

With SameSite=Strict, the browser will not send the cookie on any cross-site request — the forged form submission gets no session attached. Lax is the minimum acceptable setting for new projects; None (with Secure) re-enables cross-site sending and must only be used when genuinely required (e.g., third-party embedded widgets).

Prevention Controls: A Comprehensive Checklist

pie title CSRF Prevention Coverage by Control Type "Anti-CSRF Tokens" : 38 "SameSite Cookies" : 27 "Origin/Referer Check" : 16 "Double-Submit Cookie" : 12 "Re-auth for Sensitive Actions" : 7

Distribution reflects relative adoption weight across OWASP-recommended controls, not empirical survey data.

1. Anti-CSRF Tokens (Synchronizer Token Pattern)

The gold standard. Generate a cryptographically random token, bind it to the user session, embed it in every state-changing form or AJAX request header, and validate it server-side before processing. Tokens must be:

    1. Unpredictable (use crypto.randomBytes(32) or equivalent)
    2. Per-session at minimum; per-request for high-value operations
    3. Validated with a constant-time comparison to prevent timing attacks

Set SameSite=Strict or SameSite=Lax on all session cookies. This is a browser-enforced defense that requires no application logic changes. Chrome has defaulted to Lax when the attribute is omitted since version 80 (2020), and most modern browsers follow suit — but explicit setting is still required for compliance, older browser compatibility, and to ensure predictable behaviour across all contexts.

3. Checking Origin and Referer Headers

For server-rendered applications and APIs, validate that the Origin or Referer header matches your expected domain before processing state-changing requests. This is a defense-in-depth measure, not a primary control — headers can be absent (privacy tools strip them), so it should complement, not replace, token validation.

javascript
function validateOrigin(req) {
  const origin = req.headers.origin || req.headers.referer;
  if (!origin) return false; // fail closed
  const allowed = ['https://www.yourapp.in', 'https://app.yourapp.in'];
  return allowed.some(o => origin.startsWith(o));
}

For stateless APIs where server-side session storage is not available: set a random value in both a cookie and a request header. The server verifies they match. Because an attacker cannot read the cookie from a different origin (same-origin policy), they cannot replicate it in the header.

5. Re-authentication for Sensitive Actions

For high-value operations — password change, bank transfer above a threshold, adding a new beneficiary — require the user to re-enter their password or complete OTP verification immediately before the action. Even if a CSRF attack bypasses token checks (through a misconfiguration), it cannot supply the user's password.

🛡️
SECURITY
CSRF token validation must happen server-side on every state-changing request. Client-side-only validation (JavaScript checks before submission) provides zero protection — an attacker bypasses your JavaScript entirely by crafting raw HTTP requests or using a direct form submission.

6. Avoid GET for State-Changing Operations

GET requests should never modify state. Browsers, crawlers, and link prefetching all follow GET links without user intent. If a GET endpoint deletes a record or triggers a transfer, it is trivially exploitable without any cross-site interaction at all — just a crafted <img src="..."> tag suffices.

CSRF in Modern SPAs and APIs

Single-page applications using JWT tokens stored in localStorage are inherently CSRF-resistant — JWTs are not sent automatically by the browser, unlike cookies. However, if your SPA uses cookie-based sessions (common for security reasons — HttpOnly cookies are inaccessible to JavaScript, unlike localStorage), CSRF protection is still mandatory.

For API-first architectures:

    1. Use the X-Requested-With: XMLHttpRequest header as a lightweight signal (not a substitute for token validation)
    2. Validate Content-Type: application/json — HTML forms cannot send JSON, so a strict content-type check filters most naive CSRF attempts
    3. For fetch-based APIs, CORS policy controls which origins can make credentialed requests — but CORS is not a CSRF defense for same-origin API consumers
💡
TIP
If you use a framework (Django, Laravel, Rails, Spring Security, Next.js with iron-session), CSRF protection is often built in — but it must be explicitly enabled and not accidentally disabled via route exclusions. Audit your framework configuration before assuming you are protected.

Indian Developer Context: Where CSRF Hurts Most

CSRF vulnerabilities surface most frequently in:

    1. Fintech and BFSI portals — Transfer endpoints, beneficiary management, and KYC update flows are prime targets. RBI's cybersecurity guidelines for banks explicitly require input validation and session management controls that encompass CSRF.
    2. E-governance portals — File submission, status update, and payment confirmation endpoints on government-facing applications.
    3. B2B SaaS admin panels — Internal tools that assume "trusted network" without enforcing CSRF tokens are exploited through phishing attacks on employees.
    4. Healthcare and HR systems — Patient data updates, salary processing, leave approval workflows — all high-value state-changing operations.
The DPDP Act 2023 places accountability on data fiduciaries to implement appropriate technical safeguards. A CSRF vulnerability that allows unauthorized data modification or exfiltration is a direct technical failure under that accountability framework. See the DPDP compliance guide for the broader obligation landscape.

Running a CSRF Audit

Before fixing, you need to find all vulnerable endpoints. A systematic audit covers:

  1. Map every POST/PUT/PATCH/DELETE endpoint in the application
  2. For each endpoint: is it authenticated via cookie? If yes, is a CSRF token required?
  3. Test with a cross-origin form submission tool or Burp Suite's CSRF PoC generator
  4. Review framework configuration for accidental token exclusions (whitelisted paths, API route groups)
  5. Verify SameSite attributes on all session-related cookies
Bachao.AI's automated VAPT scanner tests for CSRF vulnerabilities across your application surface as part of a free VAPT scan. Dhisattva AI Pvt Ltd built the scanner to surface these exact class of findings in Indian-context web applications, including framework-specific misconfigurations that manual checklist reviews miss.

For compliance-grade evidence — especially if you are preparing for SEBI CSCRF, RBI IT Framework, or ISO 27001 audits — a full VAPT report documents CSRF findings with proof-of-concept, business impact, and remediation guidance in a format accepted by auditors.

🎯Key Takeaway
CSRF exploits the browser's automatic cookie behavior to forge authenticated requests. The defense is straightforward: anti-CSRF tokens on every state-changing endpoint, SameSite=Strict or Lax on session cookies, and re-authentication for high-value actions. None of these require architectural changes — they require discipline in implementation. Run a structured audit to find unprotected endpoints before an attacker does.

External References

Frequently Asked Questions

What is the difference between CSRF and XSS?
XSS injects malicious scripts into a web page that run in the victim's browser, allowing an attacker to steal cookies or data. CSRF tricks an already-authenticated user's browser into sending a forged request to a trusted site — no script injection needed. XSS attacks the user's trust in the site; CSRF attacks the site's trust in the user's browser.
Do SameSite cookies fully protect against CSRF?
SameSite cookies (Strict or Lax) are a strong browser-level defense and should be set on all session cookies. However, they are not sufficient alone — older browsers have incomplete support, and some same-site scenarios can still be exploited. Use SameSite alongside anti-CSRF tokens for defense in depth.
Are REST APIs with JWT authentication vulnerable to CSRF?
REST APIs that authenticate via JWTs stored in localStorage are generally not vulnerable to CSRF because the browser does not automatically send localStorage data with cross-site requests. However, if your API uses HttpOnly cookie-based sessions for security reasons, standard CSRF protections apply.
Is CSRF relevant for mobile apps?
Native mobile apps that call backend APIs using Authorization headers (Bearer tokens) are not vulnerable to CSRF. The risk applies to web-based flows, hybrid apps using WebViews with cookie-based sessions, and any browser-accessible endpoint that accepts cookie authentication.
How do I test my application for CSRF vulnerabilities?
The practical approach is to identify every state-changing endpoint, then attempt a cross-origin form submission to each one without a CSRF token. Burp Suite Community Edition has a built-in CSRF PoC generator. Automated scanners like the one in Bachao.AI's VAPT platform can surface CSRF-vulnerable endpoints across your entire application in a single scan.
Does the DPDP Act 2023 require CSRF protection specifically?
The DPDP Act 2023 requires data fiduciaries to implement "reasonable security safeguards" to prevent unauthorized data processing. A CSRF vulnerability that allows an attacker to modify, exfiltrate, or delete personal data constitutes a failure of that obligation and could trigger regulatory scrutiny. CSRF protection is part of baseline web application security hygiene expected under the Act.
BR

Bachao.AI Research Team

Cybersecurity Research

AI-powered security research and threat intelligence from the Bachao.AI team. Covering the latest vulnerabilities, CVEs, and cybersecurity developments affecting Indian businesses.

Get cybersecurity insights for Indian SMBs

Weekly vulnerability alerts, DPDP compliance tips, and security guides. No spam — unsubscribe anytime.

We respect your privacy. Your email is never shared.

Find out if you're exposed to this class of threat

Free automated scan — risk score in under 2 hours. No credit card required.

Scan Your Attack Surface
Find your vulnerabilitiesStart free scan →