What Is a CSRF Attack?
A cross-site request forgery attack causes an authenticated browser to send a request to a trusted application without the user intentionally authorizing that action. The browser may automatically attach session cookies, so a vulnerable server sees a valid authenticated request even though the request was initiated from an attacker-controlled origin.
CSRF is primarily an integrity problem: the attacker tries to make the victim perform an action such as changing an email address, creating an API key, updating a shipping address or transferring value. The attacker normally cannot read the protected response because browser same-origin rules still apply, but they may not need to read it if the unwanted action succeeds.
CSRF Attack Example: How a Forged Request Uses an Existing Session
Consider a banking-style application that changes a notification email using a cookie-authenticated POST request. If the endpoint accepts the request without a CSRF token or origin check, another site could try to cause the victim’s browser to submit a matching form. The important security property is that the server can distinguish an intentional state-changing action from a cross-site request that merely carries the victim’s ambient credentials.
POST /account/email HTTP/1.1
Host: app.example.com
Cookie: __Host-Session=<browser-managed session>
Content-Type: application/x-www-form-urlencoded
email=new-address@example.netA secure implementation requires an anti-CSRF value tied to the authenticated session or request context, validates trusted origins, and uses appropriate cookie attributes. If the CSRF proof is missing or invalid, the server rejects the state-changing request.
What Conditions Make CSRF Possible?
- The application relies on credentials that the browser sends automatically, such as session cookies.
- The target endpoint performs a meaningful state change.
- The request format can be triggered cross-site or the server does not verify request origin/context.
- The application does not require an unpredictable anti-CSRF token or equivalent proof.
- Authorization is valid for the victim, because CSRF can only exercise capabilities the victim account already has.
CSRF vs XSS vs CORS: Related but Different Problems
| Topic | Core problem | Primary defensive focus |
|---|---|---|
| CSRF | A browser automatically sends credentials on a request the user did not intend | CSRF tokens, Fetch Metadata, Origin checks, SameSite, safe HTTP semantics |
| XSS | Attacker-controlled script executes in the trusted origin | Output encoding, safe DOM APIs, CSP and framework protections |
| CORS | Browser policy controls which origins may read cross-origin responses or make certain non-simple requests | Exact origin allowlists and credential rules |
CORS is not a general replacement for CSRF protection. Likewise, a serious XSS flaw can undermine many CSRF defenses because script executing in the trusted origin can often obtain tokens or issue same-origin requests. Treat these as separate controls that reinforce one another.
CSRF Tokens and the Synchronizer Token Pattern
OWASP recommends using built-in framework CSRF protection where available. A common design is the synchronizer token pattern: the server generates a secret, unpredictable value associated with the user session and requires it on state-changing requests. The token should not be placed in URLs, where it can leak through history, logs or referrers.
POST /account/email
Cookie: __Host-Session=<session>
X-CSRF-Token: <unpredictable per-session or per-request value>
Content-Type: application/json
{"email":"new-address@example.net"}The server validates the CSRF token before applying the change. Stateless applications can use a carefully designed signed double-submit cookie pattern, but naive “cookie value equals request value” approaches can be vulnerable if an attacker can plant cookies for the target domain.
CSRF and REST APIs: When Is an API Vulnerable?
An API is not automatically protected from CSRF just because it returns JSON. The key question is whether the browser automatically attaches the credential. A cookie-authenticated API can be exposed to CSRF if a cross-site request can trigger a sensitive action. By contrast, an API that requires a bearer token in an Authorization header that an attacker’s site cannot cause the browser to attach automatically has a different CSRF exposure.
Do not confuse that with CORS. Restrictive CORS can limit cross-origin JavaScript, but simple browser requests and navigations still exist, and CORS is not the primary proof that a state-changing request came from your application. Use an explicit CSRF design for cookie-based browser sessions.
For SPAs and browser-to-API architectures, document where the session lives, which component issues credentials and which endpoints accept ambient cookies. Then test login, logout, password/MFA changes, API-key creation and other high-impact operations separately.
Related Ammune reading: API authorization vs authentication and OAuth API security mistakes.
How to Detect and Test for CSRF
Defensive testing should inventory every state-changing browser endpoint and verify that it rejects requests when the anti-CSRF proof is absent, invalid, expired or belongs to another session. Test alternate content types, mobile/web variants and endpoints that appear harmless but actually change server state.
- Log repeated CSRF-token validation failures without logging token values.
- Monitor sensitive changes that occur from unusual browser contexts, devices or referer/origin combinations.
- Use automated security testing to find state-changing endpoints that lack framework CSRF protection.
- Review application routes after framework upgrades or migrations; CSRF middleware can be accidentally excluded for new API prefixes.
Common CSRF Prevention Mistakes
- Relying only on CORS.
- Relying only on SameSite cookies.
- Putting CSRF tokens in URLs or logs.
- Using predictable or user-controlled CSRF values.
- Allowing GET requests to modify data.
- Applying CSRF protection only to HTML forms but not JSON endpoints that share the same cookie session.
- Skipping CSRF checks for “internal” endpoints exposed to the browser.
Login CSRF, Reauthentication and Sensitive Actions
CSRF is not limited to “change email” or “transfer funds” endpoints. Login CSRF can force a victim browser into a session controlled by the attacker, which may cause later activity to be stored in or associated with the attacker’s account. Authentication and account-linking endpoints therefore deserve the same origin and request-integrity review as ordinary state-changing routes.
For particularly sensitive actions, CSRF tokens should be paired with reauthentication or step-up authentication. A forged request should not be able to add a new authenticator, disable MFA, generate an API credential, change account recovery data or modify a payment destination merely because an old browser session is still valid.
- Protect login, logout, account-linking and security-setting endpoints deliberately.
- Require recent authentication for security-critical changes.
- Do not expose CSRF tokens to third-party scripts unnecessarily.
- Review trusted subdomains because a compromised sibling origin can weaken assumptions around cookies and request origin.
CSRF Prevention Decision Tree for REST APIs
Start with the credential model rather than the response format. Returning JSON does not make an API immune to CSRF.
- Does the browser attach the credential automatically? If the API relies on cookies, client certificates or another ambient browser credential, evaluate CSRF explicitly. If a caller must deliberately add a bearer token to the
Authorizationheader, classic browser-driven CSRF exposure is usually lower, although token theft remains a separate risk. - Does the endpoint change state? Mutations should use appropriate non-GET methods and require request-integrity protection when ambient credentials are involved.
- Can the request be initiated cross-site? Use framework CSRF defenses or a correctly designed token pattern. Origin/Referer validation and Fetch Metadata can provide additional context.
- Is the action security-sensitive? Changing MFA, recovery information, payment destinations or API credentials should also require recent or step-up authentication.
Where Runtime API Visibility Helps With CSRF-Like Abuse
CSRF must be prevented in the application through token, origin, SameSite and request-context controls. Ammune can complement those controls by surfacing unusual state-changing API behavior and repeated abuse patterns, but it does not replace correct browser-side and server-side CSRF defenses.
CSRF Prevention Checklist
- Use framework-provided CSRF protection instead of inventing token logic.
- Require unpredictable CSRF tokens on state-changing cookie-authenticated requests.
- Set session cookies with Secure, HttpOnly and an explicit SameSite policy.
- Validate Origin/host relationships for sensitive operations where practical.
- Use Fetch Metadata as an additional browser-context signal.
- Never perform state changes through GET.
- Reauthenticate or step up authentication for especially sensitive changes.
- Test every browser and API path that uses ambient credentials.
Frequently Asked Questions
What is CSRF in simple terms?
CSRF tricks an authenticated browser into sending a request the user did not intend, relying on credentials such as cookies that the browser attaches automatically.
Does SameSite prevent all CSRF attacks?
No. SameSite is valuable defense in depth, but robust applications should still use appropriate CSRF-token and origin-validation protections.
Are REST APIs vulnerable to CSRF?
They can be when authentication is based on cookies or other browser-managed credentials. APIs that require an explicit bearer token in the Authorization header are generally less exposed to classic CSRF.
Is CORS a CSRF defense?
Not by itself. CORS mainly controls whether browser scripts can read responses; some cross-site requests can still be sent.
Should GET requests use CSRF tokens?
GET should be safe and not change server state. If a GET causes a state change, the design should be fixed rather than treating GET as a protected mutation method.
Does using JWT automatically prevent CSRF?
No. The storage and transport model matters. A token that the browser attaches automatically, such as one stored in a cookie, can still create CSRF exposure. An explicit Authorization header has a different threat model.
Primary References
Protect State-Changing APIs Beyond the Browser
CSRF prevention starts with correct application controls. Ammune adds runtime API visibility so teams can see suspicious behavior around authenticated and state-changing endpoints.
