Resource library

Cyber QA

Testing for CSRF: A QA Guide (2026)

Learn testing for CSRF with practical browser tests for tokens, cookies, Origin checks, SameSite behavior, GraphQL, automation, and interview answers.

27 min read | 3,750 words

TL;DR

Testing for CSRF requires a valid baseline, a separate-origin browser fixture, systematic removal or corruption of intent signals, and an independent state oracle. A secure application rejects forged cookie-authenticated mutations before any business side effect occurs.

Key Takeaways

  • Model CSRF as a browser request-intent failure involving ambient credentials, not simply as a missing token.
  • Inventory every browser-reachable mutation, including login, logout, GraphQL, uploads, and WebSocket handshakes.
  • Challenge missing, altered, stale, duplicate, and cross-session anti-CSRF tokens one variable at a time.
  • Use Playwright to reproduce real Origin, SameSite, cookie, navigation, and CORS behavior.
  • Prove every rejected request leaves authoritative state and downstream systems unchanged.
  • Treat SameSite, Origin checks, CORS, and user confirmation as layered controls with separate test oracles.

Testing for CSRF means proving that a browser cannot be tricked by another site into submitting an authenticated, state-changing request that the application accepts. A strong QA approach checks the whole trust decision: session cookies, anti-CSRF tokens, Origin or Referer validation, SameSite behavior, content types, CORS, redirects, and the final business state.

This guide turns that security goal into repeatable manual and automated tests. Use it only against systems you own or are explicitly authorized to assess. Run destructive cases in isolated accounts and environments, and verify side effects with a trusted oracle instead of relying on the response alone.

TL;DR

Question QA answer
What makes CSRF possible? A browser attaches ambient credentials to a forged request, and the server accepts no unforgeable evidence of user intent.
What is the best primary control? A correctly generated, session-bound anti-CSRF token or an equivalent framework defense, verified on every protected mutation.
Is SameSite enough? No. It is valuable defense in depth, but deployment topology, browser behavior, top-level navigation, and same-site sibling origins still matter.
Does CORS stop CSRF? Not by itself. CORS controls whether scripts can read or send some cross-origin requests, while browsers can submit other cross-site requests without CORS approval.
What should every negative test prove? The request is rejected before protected work and no database, queue, email, payment, or audit-success side effect occurs.

1. Build the Testing for CSRF Mental Model

CSRF is a confused-deputy problem in the browser. The victim has an authenticated relationship with the target application. A page controlled by another origin causes the browser to send a request to that target. If the browser automatically attaches a session cookie or HTTP authentication credential, and the server treats that credential as sufficient proof of intent, the target may perform an action chosen by the attacker.

Three conditions usually align:

  1. The operation changes meaningful state or starts a sensitive workflow.
  2. Authentication is ambient, meaning the browser adds it without the calling page knowing the secret.
  3. The request contains no value that a cross-site page cannot obtain or no trusted-origin signal that the server enforces.

CSRF is not the same as cross-site scripting. XSS executes code in a trusted origin and can often read tokens or call same-origin APIs. CSRF normally operates from an untrusted origin and depends on the browser sending credentials. The testing for XSS guide covers that separate execution problem.

It is also not an authorization failure. The victim may be fully allowed to perform the operation. The defect is that the application cannot distinguish the victim's deliberate request from a forged one. Keep authentication, authorization, and request-intent checks separate in both test design and defect reports.

Do not begin with a famous payload. Begin with the trust rule. Write down which credential the browser adds, which evidence the server expects, and why an external origin cannot supply that evidence. Your tests should challenge each assumption independently.

2. Start Testing for CSRF with a Mutation Inventory

Inventory every operation that creates, updates, deletes, approves, transfers, publishes, uploads, invites, links, exports, or changes security settings. Include conventional forms, JSON APIs, GraphQL mutations, file uploads, WebSocket handshakes, OAuth callbacks, password and email changes, logout, and administrative actions. A route named GET /download may create an export job, while a route named POST /preview may be read-only. Classify behavior, not method names.

For each operation, record:

  • HTTP method, URL, content type, and redirect chain.
  • Authentication mechanism and cookie attributes.
  • Anti-CSRF mechanism, token location, and validation owner.
  • Origin and Referer policy, including behavior when headers are missing.
  • CORS policy and whether a simple browser request can represent the operation.
  • Required user confirmation, recent authentication, or transaction signing.
  • Observable state and downstream side effects.

Prioritize account takeover and irreversible outcomes: credential changes, recovery settings, MFA enrollment, payment destinations, API keys, role grants, consent, and data deletion. Then cover routine writes because attackers can chain low-severity actions into a larger workflow.

Use browser developer tools or an approved proxy to capture a legitimate request. Preserve one clean baseline. During each test, change one security signal while keeping identity, business input, and state constant. This isolates the control that rejected the request and prevents a validation error from masquerading as CSRF protection.

The API security testing basics guide helps expand the inventory across endpoints and trust boundaries. CSRF coverage should be traceable to the same API catalog used for functional and authorization testing.

3. Compare CSRF Defenses and Their Test Oracles

No single header or cookie attribute tells you that an application is safe. The server must enforce a coherent policy, and QA needs an observable pass or fail condition for each layer.

Defense What it proves Positive test Negative test Important limitation
Synchronizer token Request came from a page that received a session-bound secret Current token and session succeed Missing, altered, stale, or cross-session token fails XSS can often read a DOM token
Signed double-submit cookie Header or field matches a value cryptographically bound to the session Valid signed pair succeeds Attacker-chosen cookie or mismatched pair fails Naive unsigned equality is vulnerable to cookie injection patterns
Origin validation Request came from an allowed origin Exact trusted scheme, host, and port succeed Foreign, malformed, null, or disallowed sibling origin fails Header availability and proxy reconstruction need defined handling
Referer validation Navigation source is trusted when Origin is unavailable Trusted HTTPS referrer succeeds Foreign referrer fails Privacy settings can remove or trim the value
SameSite cookie Browser limits cross-site cookie attachment Intended same-site journey remains usable Cross-site fixture does not carry the protected cookie Same-site is broader than same-origin, and Lax permits some top-level behavior
Custom request header Request requires script and normally a CORS preflight Trusted frontend sends header Simple cross-site submission cannot reproduce request Weak CORS rules can undermine the assumption
User interaction Human confirms a high-risk transaction Fresh confirmation completes exact action Background or stale confirmation fails Adds friction and should supplement server checks

Avoid accepting any error as success. A forged request that receives 500 may still have committed a transaction. A request rejected for malformed JSON does not prove the same operation is protected when submitted as form data. The primary oracle is unchanged authoritative state plus absence of downstream effects.

Record expected status and stable error code, but allow the product contract to choose 400, 403, or another safe response. What matters is consistent enforcement before the mutation and a response that does not disclose token values, session details, or internal policy logic.

4. Execute a Controlled Manual CSRF Workflow

First, perform the action normally and capture the request. Confirm the business state changed once. Reset the fixture. Then replay the request with the current authenticated session while removing the anti-CSRF token. If it still succeeds, confirm that another mechanism deliberately protected it before reporting a defect. For example, exact Origin validation may be the designed control.

Next, vary the token systematically:

  1. Omit the token field or header.
  2. Send an empty value.
  3. Change one character.
  4. Reuse a token after logout and login.
  5. Pair user A's token with user B's session.
  6. Reuse a token after the documented expiry or security event.
  7. Duplicate the token parameter with conflicting values.
  8. Move it between body, query, and header to detect permissive fallback parsing.

Then reproduce the browser constraints from a separate origin that you control. Use an HTML form for application/x-www-form-urlencoded, multipart/form-data, or text/plain. Use top-level navigation and resource tags only for non-destructive lab cases. Do not send a broad payload corpus at shared systems. The goal is to show whether one real protected operation can be forged, not to create traffic volume.

Check the final state through an authorized API, database fixture, event store, or administrative view. Inspect email, queue, webhook, storage, and payment sandboxes. If the server created work and later returned an error, report the issue even when the visible response looks denied.

Finally, repeat after logout, session rotation, privilege change, and token refresh. This connects CSRF behavior with the session lifecycle described in JWT authentication testing, while recognizing that browser cookie sessions and bearer tokens have different ambient-credential properties.

5. Automate Testing for CSRF with Playwright

Browser automation is valuable because SameSite and Origin behavior belongs to the browser, not an HTTP client. The following Playwright test assumes an authorized test application exposes a profile page and POST /api/profile/email. Configure the four environment variables for disposable users. Install with npm install -D @playwright/test, install Chromium with npx playwright install chromium, and run npx playwright test csrf.spec.js.

import { test, expect } from "@playwright/test";

const appUrl = process.env.APP_URL;
const loginPath = process.env.LOGIN_PATH ?? "/login";
const username = process.env.TEST_USERNAME;
const password = process.env.TEST_PASSWORD;

test.beforeEach(async ({ page }) => {
  test.skip(!appUrl || !username || !password, "Set APP_URL and test credentials");
  await page.goto(new URL(loginPath, appUrl).href);
  await page.getByLabel("Email").fill(username);
  await page.getByLabel("Password").fill(password);
  await Promise.all([
    page.waitForURL((url) => url.origin === new URL(appUrl).origin),
    page.getByRole("button", { name: /sign in/i }).click()
  ]);
});

test("rejects a protected mutation when the CSRF token is missing", async ({ page }) => {
  const uniqueEmail = `csrf-${Date.now()}@invalid.example`;

  const result = await page.evaluate(async ({ uniqueEmail }) => {
    const response = await fetch("/api/profile/email", {
      method: "POST",
      credentials: "include",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ email: uniqueEmail })
    });
    return { status: response.status, text: await response.text() };
  }, { uniqueEmail });

  expect([400, 403]).toContain(result.status);

  await page.goto(new URL("/settings/profile", appUrl).href);
  await expect(page.getByLabel("Email")).not.toHaveValue(uniqueEmail);
});

test("rejects a token copied from a different authenticated session", async ({ browser }) => {
  const contextA = await browser.newContext();
  const contextB = await browser.newContext();
  const pageA = await contextA.newPage();
  const pageB = await contextB.newPage();

  // Replace these helpers with login steps for two disposable test users.
  await pageA.goto(new URL("/settings/profile", appUrl).href);
  await pageB.goto(new URL("/settings/profile", appUrl).href);
  const tokenA = await pageA.locator('meta[name="csrf-token"]').getAttribute("content");

  const response = await pageB.request.post(new URL("/api/profile/email", appUrl).href, {
    headers: { "x-csrf-token": tokenA ?? "" },
    data: { email: `cross-session-${Date.now()}@invalid.example` }
  });

  expect([400, 403]).toContain(response.status());
  await contextA.close();
  await contextB.close();
});

Adapt selectors, login, token location, and status to the actual contract. The second example intentionally marks the two-user login as product-specific work, so do not treat it as complete until each context has a verified identity. Never broaden the assertion to any non-2xx status. Assert the documented CSRF code and state once the application contract exposes them.

6. Test Token Generation, Binding, Rotation, and Parsing

A token should be unpredictable, validated server-side, and associated with the correct security context. QA does not need to estimate entropy from a handful of samples. Instead, inspect the design with developers, confirm a cryptographically secure generator is used, and test observable binding and lifecycle rules. A token that merely encodes the user ID is not a secret.

For synchronizer tokens, confirm user A cannot use user B's token, an anonymous token cannot authorize an authenticated mutation, and logout invalidates the old session relationship. Decide whether tokens are per session, per request, or per action, then test that documented model. Per-request rotation can create usability and concurrency defects, so open two tabs and submit legitimate forms in different orders.

For signed double-submit patterns, verify the server validates a signature or message authentication code bound to the authenticated session. Merely checking that a request value equals a cookie value can be unsafe when an attacker can plant a cookie through a related host or other application behavior. Test subdomain boundaries and cookie Domain configuration in an approved environment.

Parsing deserves its own cases. Duplicate headers may be combined, rejected, or normalized by proxies. Duplicate body parameters may use first-value or last-value semantics. Send conflicting values and require a safe rejection at one clearly owned layer. Check case handling for header names without assuming value case-insensitivity. Ensure logs never record token values.

If a token is returned in HTML, verify it is not placed in URLs, browser history, referrer-bearing links, analytics events, or server access logs. If JavaScript reads it from a cookie, that cookie cannot be HttpOnly, so document the tradeoff and keep XSS defenses strong.

7. Validate SameSite, Origin, Referer, CORS, and Proxies

Cookie testing needs a precise site model. SameSite uses the registrable site concept and scheme, while the same-origin policy includes scheme, host, and port. Two sibling subdomains can be same-site but cross-origin. If an untrusted tenant controls one sibling, SameSite alone may not isolate the sensitive application.

Verify Secure, HttpOnly, SameSite, Domain, Path, expiry, and host-prefix choices on every authentication cookie. Test the actual HTTPS deployment. Localhost behavior and automation shortcuts can hide production differences. Confirm legacy cookies, remember-me cookies, and load-balancer cookies do not accidentally restore a protected session.

Origin validation should compare parsed origins against an exact allowlist. Test trusted origin, foreign origin, sibling origin, wrong scheme, wrong port, suffix tricks, prefix tricks, mixed case where relevant, trailing dot behavior, and the literal null origin. The expected response when Origin is absent must be documented. A permissive fallback that accepts every missing header can erase the control for some request classes.

Reverse proxies complicate target-origin reconstruction. The application may see an internal host while the browser addressed a public host. Test through the real ingress and ensure only trusted proxies can supply forwarded host or protocol information. An attacker-controlled X-Forwarded-Host must not make an evil origin appear trusted.

CORS is not a general CSRF control. A simple form submission may reach the server without preflight. If the application intentionally relies on JSON plus a custom header, test that no alternate content type reaches the same action and that CORS never reflects arbitrary origins with credentials. Preflight denial is useful evidence, but still verify the mutation endpoint rejects the forged request itself.

8. Cover Login CSRF, Logout, OAuth, and High-Risk Workflows

Login CSRF forces a victim into an account selected by an attacker. The victim may then enter personal or payment data into the wrong account. Test whether the login request is bound to a page or authorization transaction, whether existing sessions are handled safely, and whether external identity callbacks validate transaction state. Do not assume login is harmless because it creates rather than uses a session.

OAuth and OpenID Connect flows use state and nonce for specific purposes, and Proof Key for Code Exchange binds authorization code use. Test correlation values for presence, unpredictability, exact callback binding, single use, expiry, and behavior across parallel tabs. Never replace protocol-specific validation with a generic hidden field. Use provider sandboxes and disposable clients.

Logout CSRF can disrupt users and can support attack chains. Decide whether logout is state-changing enough to require POST and CSRF validation. Verify a cross-site image or link cannot terminate a session if the documented policy forbids it. Also test that a rejected logout does not partially clear client state while leaving server credentials active.

High-risk workflows deserve more than a generic token. Password, recovery, MFA, payment, and administrator operations may require recent authentication, transaction details in the confirmation screen, one-time authorization, or step-up verification. Test that confirmation is bound to the exact action and values. Changing the destination after confirmation must invalidate approval.

Redirects can change request behavior. Trace 302, 303, 307, and 308 flows in the actual stack, especially around identity providers and canonical hosts. Ensure a request rejected on one host is not redirected to a weaker alias that performs it.

9. Test JSON, GraphQL, Uploads, and Unusual Request Surfaces

JSON APIs are often safer from classic form-based CSRF only because browsers cannot submit arbitrary application/json with a plain form. That is an environmental constraint, not proof of user intent. Test whether the endpoint also accepts text/plain, form encoding, missing content type, vendor types, or a method override. Require the documented media type and apply CSRF validation where cookie authentication remains ambient.

GraphQL commonly puts many mutations behind one URL. Inventory operation names and resolver effects, not only /graphql. Verify CSRF enforcement before execution for every cookie-authenticated mutation and any query with side effects. Batching can mix protected and unprotected operations, so test atomicity and per-operation decisions according to the server's supported batch contract.

Multipart uploads can be submitted by HTML forms. Test avatar, import, attachment, and document endpoints with missing and mismatched tokens. Confirm temporary storage, virus scanning, and job queues are not created before CSRF rejection. A later validation failure does not undo the cost or exposure of an early upload.

WebSocket connections start with an HTTP handshake, and browsers attach eligible cookies. Validate the handshake Origin against an allowlist and authorize every operation after connection. CSRF-like cross-site WebSocket hijacking is not solved by a token checked only on the page that opens the socket. Test reconnects, credential rotation, and sibling origins.

Also inspect beacon endpoints, method-override headers, legacy RPC routes, image transformation URLs, report generation, and mobile web fallbacks. Any browser-reachable route using ambient credentials and changing state belongs in scope.

10. Make CSRF Regression Tests Stable and Useful

Security tests become noisy when fixtures share accounts or assert only transient responses. Give each test a disposable user and unique business value. Reset through a trusted setup API. Keep the forgery action separate from the verification action, and use an administrative oracle that is not subject to the same denial.

Create a small mandatory suite for every protected mutation pattern:

  • Valid session plus valid token succeeds once.
  • Valid session plus missing token fails with unchanged state.
  • Valid session plus malformed token fails.
  • Cross-session token fails.
  • Foreign Origin fails according to policy.
  • Exact trusted Origin succeeds.
  • Logged-out or expired session follows authentication policy.
  • Duplicate submission follows idempotency policy.

Run framework-level unit or integration tests for middleware coverage and a smaller browser suite for real cookie and origin behavior. Add a route inventory check that fails when a new cookie-authenticated mutation lacks the declared CSRF policy. This catches omissions earlier than payload scanning.

Do not disable SameSite or CSRF controls globally in test environments. Provide supported test hooks that generate valid tokens or authenticated storage state. Production-like ingress is important for forwarded headers and cookie scope. Mask credentials and tokens in traces, videos, console output, and CI artifacts.

When a test fails, capture request method, normalized route, origin class, token case, session fixture, response code, correlation ID, and state result. Do not attach live cookies or token secrets to the defect.

11. Report Severity, Root Cause, and Remediation Evidence

A useful CSRF report names the operation, victim prerequisites, authentication mechanism, missing or bypassed control, realistic outcome, and verified side effect. Include a minimal reproduction against a disposable record. Distinguish a theoretical cross-site request from a completed state change. Note whether SameSite or browser behavior reduces reach, but do not describe it as a complete fix when another supported path remains vulnerable.

Severity depends on the action and victim. Changing an administrator's recovery method is very different from toggling a harmless preference. Consider user interaction, privilege, data sensitivity, reversibility, detectability, and whether the action enables a chain. Avoid inflating impact with outcomes you did not verify.

Recommend root-cause fixes: framework-supported token validation, strict origin checks, correct SameSite cookies, narrow CORS, reauthentication for sensitive actions, and removal of state changes from GET. Do not recommend checking Referer alone without a missing-header policy, and do not recommend a custom header unless alternate simple request formats are rejected.

Retest at three levels. Confirm the original reproduction fails. Confirm a legitimate request still works across tabs and supported browsers. Confirm nearby routes using the same middleware are protected. Then verify logs show a bounded rejection reason without secrets and that no side effect occurred.

For response distinctions between missing identity and refused intent or permission, use the HTTP 401 vs 403 testing guide. The public code should follow the product contract, while internal telemetry should distinguish authentication, authorization, and CSRF decisions.

Interview Questions and Answers

Q: What is CSRF, and what conditions make it possible?

CSRF is a forged browser request that performs an action with the victim's ambient credentials. I look for a sensitive state change, automatically attached authentication such as cookies, and no unforgeable evidence of user intent. My test proves the action occurred, not merely that the request reached the server.

Q: How do you test an anti-CSRF token?

I start with a valid baseline, then test missing, empty, altered, expired, reused, duplicate, and cross-session values one at a time. I verify the exact rejection contract and prove state and downstream effects are unchanged. I also test legitimate parallel tabs so strict rotation does not break real users.

Q: Is SameSite sufficient to prevent CSRF?

No. SameSite is strong defense in depth, but behavior varies by mode and request context, and same-site sibling origins may still be untrusted. I test the real deployment and keep a server-side intent check for sensitive operations.

Q: Why does CORS not automatically prevent CSRF?

CORS primarily controls cross-origin script access and preflighted requests. Browsers can still submit simple forms or navigate across sites without granting the attacker read access. I test whether any supported request shape can perform the mutation with ambient credentials.

Q: What is login CSRF?

Login CSRF makes the victim authenticate into an account chosen or controlled by the attacker. The victim can unknowingly add data to that account. I test transaction correlation on login and identity callbacks, including parallel tabs and stale state values.

Q: How do you automate CSRF testing?

I combine integration tests for token middleware with Playwright tests for real browser cookie, Origin, SameSite, and navigation behavior. Every negative test uses a separate authoritative state oracle. I keep a route-policy inventory so new mutations cannot silently omit protection.

Q: How do CSRF and XSS differ?

CSRF sends a request from an untrusted origin using credentials the browser attaches. XSS executes attacker-controlled script inside the trusted origin. XSS can defeat many token defenses, so both require independent coverage.

Q: What evidence belongs in a CSRF defect?

I include the affected operation, victim state, forged request shape, missing control, response, and proven business side effect on a disposable record. I omit live secrets. I also state realistic prerequisites and the smallest root-cause remediation.

Common Mistakes

  • Calling every rejected request CSRF-protected without checking why it failed.
  • Treating POST, JSON, CORS, or SameSite as a complete defense by itself.
  • Testing only token absence and ignoring cross-session binding, duplicates, rotation, and alternate parsers.
  • Using an HTTP client to infer browser cookie and Origin behavior.
  • Verifying only the response while a database write, queue message, upload, or email already occurred.
  • Forgetting login, logout, GraphQL, upload, WebSocket, legacy, and administrative workflows.
  • Disabling security middleware in test environments, which removes meaningful regression coverage.
  • Logging session cookies or anti-CSRF tokens in CI evidence.
  • Recommending broad custom controls instead of the framework's maintained protection.
  • Running destructive forged requests against shared or production data without explicit authorization.

Conclusion

Testing for CSRF is a trust-validation exercise, not a one-payload scan. Inventory browser-reachable mutations, identify ambient credentials, challenge every intent signal, reproduce real cross-site constraints, and prove protected state never changes when evidence is missing or invalid.

Start with the highest-risk cookie-authenticated action in a disposable account. Capture a valid request, remove one control at a time, exercise it from a separate origin with Playwright, and verify the final state independently. Once that path is reliable, turn the same model into a route-wide regression matrix.

Interview Questions and Answers

Explain CSRF and its prerequisites.

CSRF is a forged browser request that uses the victim's ambient authentication. It generally needs a meaningful state change, automatically attached credentials, and no unforgeable evidence of user intent. I prove it by observing the unauthorized state change, not just request delivery.

How would you test an anti-CSRF token?

I begin with a successful baseline, then vary missing, empty, altered, stale, duplicate, and cross-session values separately. I assert the expected rejection and verify database and downstream state. I also test legitimate parallel tabs and rotation.

Why is SameSite defense in depth rather than the only control?

SameSite behavior depends on mode and request context, and same-site does not mean same-origin. Sibling origins can matter, and supported navigation patterns may still carry cookies. Sensitive mutations should retain a server-validated intent signal.

Does CORS prevent CSRF?

Not generally. CORS governs cross-origin script access and preflighted requests, while simple forms and navigations can still reach a server. I test every accepted request shape and the endpoint's own protection.

How do you automate CSRF tests?

I combine middleware integration tests with Playwright coverage for cookie, Origin, SameSite, CORS, and redirects. Each negative browser action has an independent state check. I also maintain a route-policy inventory for new mutations.

What is login CSRF?

Login CSRF places a victim into an account selected by the attacker. The victim may then add personal or payment data to that account. I test login and identity callback correlation, parallel tabs, stale state, and session replacement.

What should a CSRF defect report contain?

It should identify the operation, ambient credential, missing or bypassed control, victim prerequisites, forged request, and proven business side effect. I use disposable records, redact secrets, and recommend a framework-supported root-cause fix.

How do you verify a CSRF fix?

I rerun the original cross-site reproduction, confirm unchanged state, and verify legitimate same-origin flows still work. Then I test sibling routes using the same middleware, alternate content types, session lifecycle, and safe logging.

Frequently Asked Questions

What is the first step when testing for CSRF?

Inventory state-changing operations and capture one legitimate request for each pattern. Identify the ambient credential, anti-CSRF evidence, Origin policy, cookie attributes, and authoritative state oracle before changing any input.

How do I test a CSRF token?

Run separate cases for a missing, empty, altered, expired, reused, duplicate, and cross-session token. Keep the identity and business input fixed, then verify both the expected rejection and unchanged state.

Does a SameSite cookie completely stop CSRF?

No. SameSite reduces cross-site cookie attachment, but mode, navigation type, scheme, and same-site sibling origins affect behavior. Keep server-side intent validation for sensitive operations and test the real deployment.

Can a JSON API be vulnerable to CSRF?

Yes, especially when it uses cookie authentication and accepts alternate content types or weak CORS. Test JSON, text, form, missing content type, method overrides, and custom-header enforcement against the same mutation.

Why should CSRF tests use a browser?

Browser rules determine cookie attachment, Origin headers, SameSite behavior, preflight, redirects, and navigation. An HTTP client can test server validation but cannot faithfully prove the browser attack conditions.

What status code should a CSRF rejection return?

The application contract may choose 400, 403, or another safe response. QA should assert the documented code and stable error shape, while prioritizing rejection before mutation and absence of sensitive detail.

How is CSRF different from XSS?

CSRF sends a forged request from an untrusted origin with credentials the browser attaches. XSS executes attacker-controlled code inside the trusted origin and can often bypass token defenses, so each requires separate tests.

Related Guides