Information Security 22 min read

Understanding Cross‑Site Request Forgery (CSRF) and Effective Defenses

This article explains the fundamentals of Cross‑Site Request Forgery (CSRF), illustrates typical attack scenarios and payloads, and details multiple defense strategies including CSRF tokens, SameSite cookies, and best‑practice validation techniques for web.

System Architect Go
System Architect Go
System Architect Go
Understanding Cross‑Site Request Forgery (CSRF) and Effective Defenses

Cross‑site request forgery (CSRF)

In this section we explain what CSRF is, describe common CSRF vulnerability examples, and show how to defend against CSRF attacks.

What is CSRF

Cross‑site request forgery (CSRF) is a web security vulnerability that allows an attacker to trick a user into performing actions they did not intend. The attacker can partially bypass the same‑origin policy.

Impact of a successful CSRF attack

In a successful CSRF attack the attacker can cause the victim to change their email address, password, or perform a fund transfer. Depending on the operation, the attacker may gain full control of the user’s account, and if the victim holds privileged roles, the attacker may control all data and functionality of the application.

How CSRF works

To make a CSRF attack possible, three key conditions must be satisfied:

Relevant action – the attacker has a reason to induce a specific action in the target application (e.g., privilege change or user‑specific data modification).

Cookie‑based session handling – the request relies solely on a session cookie to identify the user, with no additional session tracking or request verification.

No unpredictable request parameters – the request does not contain values that the attacker cannot guess or determine.

Assume an application provides a feature to change a user’s email address. When the user performs this action the following HTTP request is sent:

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE

[email protected]

This example satisfies the CSRF requirements:

The action (changing the email address) is of interest to the attacker.

The application uses a session cookie to identify the requester.

The attacker can easily determine the required request parameters.

With these conditions the attacker can craft a malicious HTML page:

<html>
  <body>
    <form action="https://vulnerable-website.com/email/change" method="POST">
      <input type="hidden" name="email" value="[email protected]" />
    </form>
    <script>document.forms[0].submit();</script>
  </body>
</html>

If the victim visits the attacker’s page, the following occurs:

The attacker’s page triggers an HTTP request to the vulnerable site.

If the user is logged in, the browser automatically includes the session cookie (assuming SameSite cookies are not used).

The vulnerable site processes the request as if it originated from the victim and changes the email address.

Note: although CSRF is typically described in the context of cookie‑based sessions, it can also appear when the application automatically adds other credentials such as HTTP Basic authentication or certificate‑based authentication.

How to construct a CSRF attack

Manually creating the HTML for a CSRF attack can be cumbersome, especially when many parameters are required or when the request has other anomalies. The simplest method is to use the CSRF PoC generator in Burp Suite Professional.

How to deliver CSRF

The delivery mechanism is similar to reflected XSS: the attacker places malicious HTML on a site they control and lures the victim to visit it, e.g., via email or social media. Simple CSRF attacks may use the GET method and be fully self‑contained in a single URL.

<img src="https://vulnerable-website.com/email/[email protected]">

Defending against CSRF attacks

The most effective defense is to include a CSRF token in relevant requests. The token should be:

Unpredictable and high‑entropy.

Bound to the user’s session.

Strictly validated for each operation before execution.

Additional defenses that can be used together with a CSRF token are SameSite cookies.

Common CSRF vulnerabilities

The most interesting CSRF vulnerabilities arise from improper validation of the CSRF token.

When a token is required, a typical request might look like:

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&[email protected]

Even with a token, many implementations contain flaws such as:

Token validation depends on request method

Some applications validate the token only for POST requests; an attacker can switch to GET to bypass validation.

GET /email/[email protected] HTTP/1.1
Host: vulnerable-website.com
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

Token validation depends on token presence

If the token is omitted, validation may be skipped entirely.

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

[email protected]

Token not bound to user session

Some applications store issued tokens in a global pool and accept any token from that pool, allowing an attacker to obtain a valid token with their own account and reuse it.

Token bound only to a non‑session cookie

When the CSRF token is stored in a separate cookie that is not the session cookie, an attacker who can set cookies in the victim’s browser may inject a valid token.

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv

csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&[email protected]

Double‑submit cookie token

Some implementations copy the token into both a cookie and a request parameter and only compare the two values. This can be abused if the attacker can set the cookie.

POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa

csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&[email protected]

Referer‑based CSRF defense

Some applications validate the HTTP Referer header to ensure the request originates from the same domain. This method is often weak and can be bypassed by omitting the header or by manipulating the URL.

<meta name="referrer" content="never">

CSRF tokens

CSRF tokens are unique, secret, unpredictable values generated by the server and sent to the client, which must include them in subsequent requests. Because an attacker cannot guess the token, the request will be rejected if the token is missing or invalid.

How CSRF tokens should be generated

Tokens should contain high entropy and be generated with a cryptographically strong pseudo‑random number generator (PRNG), optionally combined with user‑specific entropy and hashed.

How to transmit CSRF tokens

Tokens are typically placed in hidden form fields submitted via POST:

<input type="hidden" name="csrf-token" value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz" />

Alternatively, tokens can be sent in custom request headers, which prevents them from being exposed in URLs or Referer headers. Tokens should never be stored in cookies.

How to validate CSRF tokens

When a request arrives, the server must compare the token supplied in the request with the token stored in the user’s session, rejecting the request if they do not match, regardless of HTTP method or content type.

XSS vs CSRF

This section compares Cross‑Site Scripting (XSS) and CSRF, and discusses whether CSRF tokens can mitigate XSS attacks.

Differences between XSS and CSRF

XSS allows an attacker to execute arbitrary JavaScript in the victim’s browser, while CSRF forces the victim to perform unintended actions. XSS is generally more severe because it can be used to perform any action the user can, whereas CSRF is limited to a subset of actions.

Can CSRF tokens defend against XSS?

In some cases a properly validated CSRF token can prevent the exploitation of a reflected XSS vulnerability that triggers a state‑changing request. However, if any XSS exists elsewhere in the application, the attacker can obtain a valid token and still perform malicious actions.

SameSite cookies

Some sites use SameSite cookies as an additional defense against CSRF. The SameSite attribute can be set to Strict or Lax in the Set‑Cookie header.

SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;

SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax;

Strict prevents the cookie from being sent on any cross‑site request, while Lax allows it on top‑level navigation GET requests. Relying solely on SameSite is not recommended; it should be combined with CSRF tokens for robust protection.

CSRFXSSweb securityCross Site Request ForgeryCSRF tokenSameSite cookies
System Architect Go
Written by

System Architect Go

Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.