CSRF is a web application security vulnerability that exploits the trust between a website and an authenticated user's browser. Fortunately, developers can significantly reduce this risk through secure CSRF tokens, SameSite cookies, origin validation, and modern application security practices.
A CSRF (Cross-Site Request Forgery) token is a unique, unpredictable value generated and validated by a web application to verify that a state-changing request is legitimate. It helps prevent attackers from tricking authenticated users into unknowingly submitting unauthorized requests, such as transferring money, changing account details, or modifying passwords.
In this guide, we explain how CSRF attacks work, why they happen, how security tokens prevent them, and how developers can implement effective protection in modern web applications.
1. What Is Cross-Site Request Forgery (CSRF)?
Cross-Site Request Forgery, commonly known as CSRF or XSRF, is an attack in which a malicious website or application tricks an authenticated user's browser into sending an unwanted request to another website where the user is already logged in.
The attack takes advantage of the browser's automatic handling of authentication credentials, particularly session cookies. When a user is authenticated, the browser may automatically attach the relevant cookies to requests sent to the trusted website.
If the application does not verify whether a state-changing request was genuinely initiated through its intended interface, an attacker may exploit the authenticated session.
You log into your bank account and leave the session active. You then visit a malicious website containing a hidden form. That form attempts to send a money-transfer request to your bank. If the bank does not have effective CSRF protection, your browser may automatically include its authentication cookie, allowing the forged request to reach the application.
The important distinction is that the attacker does not necessarily need to steal your password or session cookie. The attack abuses the browser's existing authenticated session.
2. How Does a CSRF Attack Work?
To understand how Cross-Site Request Forgery works, consider the following scenario involving Ella, a 22-year-old web developer who has recently launched her first online banking application.
Ella's Security Mistake
Ella developed a simple banking platform where users could:
- Log into their accounts.
- Check their account balances.
- Transfer money to other users.
- Update their personal information.
Her application used session cookies to authenticate users. However, she overlooked an important security requirement: validating whether sensitive requests originated from her application's legitimate interface.
One day, an attacker created a malicious website containing a hidden form designed to submit a transfer request to Ella's banking application.
Example of a Forged HTML Form
The following simplified example illustrates the type of request an attacker might attempt to trigger:
<form action="https://example.com/transfer"
method="POST">
<input type="hidden"
name="amount"
value="500" />
<input type="hidden"
name="to_account"
value="123456" />
<input type="submit"
value="Click Here" />
</form>
This example is illustrative. An attacker could also attempt to submit the form automatically rather than relying on the victim to click it.
If a user is authenticated to the vulnerable banking application, the browser may automatically attach the relevant session cookie when submitting a request to that application.
The Four Stages of a CSRF Attack
- Authentication: The user logs into a legitimate web application.
- Malicious interaction: The user visits an attacker-controlled website or interacts with malicious content.
- Forged request: The malicious website attempts to trigger a state-changing request to the trusted application.
- Server validation: If the application lacks effective CSRF protection, it may process the forged request using the user's authenticated session.
This is why secure applications must verify more than whether a valid session cookie is present.
3. What Is a CSRF Security Token?
A CSRF security token is a unique, secret, and unpredictable value that a web application uses to validate requests that change application state.
The server generates the token and associates it with the appropriate user session or security context. The application then delivers the token to its legitimate interface, usually as a hidden form field or through a trusted application response.
When the user submits a protected form, the token is sent back to the server. The server validates it before processing the requested operation.
How Does a CSRF Token Work?
- Token generation: The server generates a cryptographically secure, unpredictable token.
- Token delivery: The token is included in the legitimate application page or response.
- Request submission: The client includes the token when submitting a protected request.
- Server validation: The server checks that the submitted token is valid and associated with the appropriate session or security context.
- Request decision: The server processes a valid request and rejects an invalid or missing token.
Example: CSRF Token in an HTML Form
A server-rendered application might generate a form containing a CSRF token like this:
<form method="POST" action="/transfer">
<input type="hidden"
name="csrf_token"
value="SERVER_GENERATED_TOKEN" />
<input type="number"
name="amount" />
<input type="text"
name="to_account" />
<button type="submit">
Transfer Money
</button>
</form>
The value shown is a placeholder, not a real security token. In a production application, the server must generate the value securely and validate it when the form is submitted.
Simply adding a hidden field does not provide protection. The server-side validation is essential.
4. CSRF Token Implementation: JavaScript and ASP.NET Core
Implementing CSRF protection correctly requires coordination between the browser and the server. The exact approach depends on the technology stack and application architecture.
Example A: JavaScript Fetch API
For a server-rendered application, the server can safely include the generated CSRF token in the page. JavaScript can then send it in a custom request header.
Example HTML:
<meta name="csrf-token"
content="SERVER_GENERATED_TOKEN">
<button id="transferButton">
Submit Transfer
</button>
Example JavaScript:
const csrfToken =
document.querySelector(
'meta[name="csrf-token"]'
).content;
document.getElementById(
"transferButton"
).addEventListener("click", async () => {
const response = await fetch("/transfer", {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken
},
body: JSON.stringify({
amount: 500,
to_account: "123456"
})
});
if (!response.ok) {
throw new Error("Transfer request failed");
}
console.log("Request accepted");
});
Example B: ASP.NET Core Antiforgery Protection
ASP.NET Core provides built-in antiforgery services. Developers should use these framework-supported mechanisms instead of manually generating predictable tokens or implementing their own token-validation system unnecessarily.
For a Razor-based form, the framework can generate the appropriate antiforgery token:
<form asp-action="Transfer"
method="post">
<input type="number"
name="amount" />
<input type="text"
name="to_account" />
<button type="submit">
Transfer
</button>
</form>
ASP.NET Core's form tag helper generates the antiforgery token for supported POST forms when configured appropriately.
The controller can validate the token using the framework attribute:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Transfer(
decimal amount,
string to_account)
{
// Perform server-side validation.
// Verify the authenticated user's
// authorization and account ownership.
// Execute the transaction securely.
return Ok("Request accepted");
}
The framework validates the antiforgery token before the protected action executes. Developers must still implement proper authorization, business validation, transaction controls, and secure session management.
5. CSRF Protection Techniques Beyond Security Tokens
CSRF tokens are an important security control, but effective web application security should use multiple defensive layers.
1. SameSite Cookies
The SameSite cookie attribute controls whether browsers send cookies in cross-site contexts.
It supports three commonly used settings:
- Strict: Prevents cookies from being sent in most cross-site contexts.
- Lax: Allows cookies in certain top-level cross-site navigations using safe HTTP methods.
- None: Allows cross-site cookie sending and requires the Secure attribute.
For example:
Set-Cookie: sessionid=VALUE;
Secure;
HttpOnly;
SameSite=Lax
SameSite is a valuable additional security layer, but it should not automatically be considered a replacement for CSRF tokens in applications that require stronger protection.
2. Origin and Referer Validation
Applications can inspect the Origin header and, where appropriate, the Referer header to determine whether a request originated from an expected website.
The server should compare the source origin against a trusted, configured origin. It must perform exact origin validation rather than relying on loose substring matching.
If the headers are missing or contain an untrusted origin, the application should follow an explicit fallback security policy rather than automatically accepting the request.
3. Custom Request Headers
For AJAX and API-based applications, developers can transmit a CSRF token through a custom request header, such as:
X-CSRF-Token: RANDOM_TOKEN_VALUE
This approach is particularly useful for applications built with JavaScript frameworks. It still requires a server-side validation strategy and carefully configured CORS policies.
4. Fetch Metadata Headers
Modern browsers can provide Fetch Metadata headers that help servers understand the context in which a request was initiated.
One useful header is:
Sec-Fetch-Site: cross-site
Servers can use this information as an additional defense by rejecting unexpected cross-site state-changing requests. A fallback policy is still important for clients that do not provide these headers.
5. Reauthentication for Sensitive Operations
For particularly sensitive operations, such as changing account recovery information or transferring substantial amounts of money, applications can require additional confirmation.
Depending on the risk, this may involve:
- Re-entering a password.
- Multi-factor authentication.
- Transaction confirmation.
- Step-up authentication.
These controls reduce the consequences of unauthorized activity but do not replace proper CSRF validation.
6. CSRF vs XSS vs SQL Injection: Understanding the Differences
CSRF, Cross-Site Scripting (XSS), and SQL Injection are three different web application security vulnerabilities. Although all can affect application security, they exploit different weaknesses.
| Comparison | CSRF | XSS | SQL Injection |
|---|---|---|---|
| Full form | Cross-Site Request Forgery | Cross-Site Scripting | SQL Injection |
| Main weakness | Missing request-intent validation | Improper handling of untrusted content | Unsafe database query construction |
| Attack target | Authenticated user's session | Application users and browsers | Database operations |
| Typical impact | Unauthorized actions | Script execution in a user's browser | Unauthorized database access or modification |
| Primary defense | CSRF tokens and request validation | Output encoding and safe input handling | Parameterized queries |
These vulnerabilities can sometimes be combined in a larger attack. Therefore, organizations should adopt a complete application security strategy rather than relying on one protective mechanism.
For additional protection at the application traffic layer, explore our guide to Web Application Firewall (WAF) protection, which explains how WAF solutions help identify and filter malicious web requests.
7. Real-World Applications of CSRF Protection
CSRF protection is particularly important in applications that perform sensitive operations using authenticated browser sessions.
Banking and Financial Applications
Online banking systems must protect operations such as money transfers, payment approvals, beneficiary management, and changes to account information.
A valid authentication cookie alone should never be treated as proof that the user intentionally initiated a transaction.
E-Commerce Platforms
E-commerce websites handle customer addresses, account details, order management, and payment-related actions. CSRF protection helps prevent attackers from triggering unauthorized account changes or other protected operations.
Social Media Platforms
Social networks need to protect actions such as changing account settings, publishing content, modifying privacy preferences, and managing connected applications.
Enterprise Applications
Business applications frequently handle confidential information, employee records, financial approvals, and administrative operations. Effective request validation helps reduce the risk of unauthorized changes through authenticated browser sessions.
Any application that uses browser-based authentication and allows users to perform state-changing operations should evaluate CSRF risks. The required protection depends on its authentication architecture, endpoints, and threat model.
8. Common CSRF Prevention Mistakes Developers Should Avoid
Even experienced developers can introduce security weaknesses when implementing CSRF protection incorrectly.
| Common mistake | Why it is dangerous | Better practice |
|---|---|---|
| Generating predictable tokens | Attackers may be able to guess them. | Use cryptographically secure token generation. |
| Validating tokens only in JavaScript | Client-side checks can be bypassed. | Always validate on the server. |
| Relying only on SameSite cookies | Some application architectures and attack scenarios require additional defenses. | Combine appropriate controls. |
| Using GET for state changes | Safe-method assumptions can be violated. | Use POST, PUT, PATCH, or DELETE for state changes. |
| Putting tokens in URLs | Tokens may leak through logs, browser history, or referrer information. | Use protected form fields or request headers. |
| Ignoring API endpoints | API operations may also be vulnerable when browser credentials are automatically included. | Apply appropriate API-specific protections. |
| Allowing unrestricted CORS | Weak origin policies can undermine custom-header protections. | Allow only trusted origins. |
9. CSRF Security Checklist for Developers
Use this practical checklist when developing, reviewing, or auditing a web application.
- Use the framework's built-in antiforgery protection where available.
- Generate unpredictable CSRF tokens using secure mechanisms.
- Validate tokens on the server for protected state-changing requests.
- Ensure GET and other safe HTTP methods do not modify application state.
- Configure session cookies with appropriate Secure, HttpOnly, and SameSite attributes.
- Validate Origin and Referer headers where appropriate.
- Consider Fetch Metadata request validation.
- Restrict CORS to explicitly trusted origins.
- Require additional confirmation for high-risk transactions.
- Test all sensitive endpoints for CSRF vulnerabilities.
- Monitor and investigate suspicious request patterns.
- Keep frameworks, dependencies, and security configurations updated.
Good security also depends on everyday practices. Read our guide on essential cyber hygiene practices for more ways to reduce common digital security risks.
10. CSRF Protection and the Broader Cybersecurity Strategy
Preventing CSRF attacks is one component of a broader application security program. Organizations should combine request validation with secure authentication, access control, encryption, vulnerability testing, monitoring, and incident response.
For example, a company operating an online financial platform should not rely exclusively on CSRF tokens. It should also verify user authorization, validate transaction details, protect sensitive information, and maintain audit logs.
Protecting customer information is equally important. Explore our guide to protecting Personally Identifiable Information (PII) to understand how sensitive information can be exposed and how organizations can reduce privacy risks.
Organizations can also strengthen access management by adopting a Zero Trust security model. Its principles of continuous verification and least-privilege access complement secure application development.
For a wider overview of organizational protection, see our comprehensive cybersecurity strategy.
11. Frequently Asked Questions About CSRF
1. What is a CSRF attack in simple terms?
A CSRF attack tricks an authenticated user's browser into sending an unwanted request to a trusted website. For example, an attacker might attempt to make a logged-in banking user submit an unauthorized transaction without their knowledge.
2. What is the main purpose of a CSRF token?
A CSRF token helps a server verify that a protected request was submitted through a legitimate application interaction. The server checks the token before processing sensitive state-changing operations.
3. Are CSRF attacks still possible with modern browsers?
Yes. Modern browsers provide useful protections, including SameSite cookies and Fetch Metadata headers, but applications must still implement appropriate server-side defenses based on their authentication and request architecture.
4. Is a CSRF token the same as a session ID?
No. A session ID identifies or references an authenticated session, whereas a CSRF token helps validate the legitimacy of a protected request. They serve different security purposes.
5. Does HTTPS prevent CSRF attacks?
No. HTTPS encrypts communication between the browser and server, protecting data in transit. However, it does not independently verify whether an authenticated user intentionally initiated a particular request.
6. What is the difference between CSRF and XSS?
CSRF tricks a user's authenticated browser into sending an unwanted request to a website. XSS involves injecting malicious scripts into content that executes in another user's browser. Their attack mechanisms and primary defenses are different.
7. Can SameSite cookies replace CSRF tokens?
SameSite cookies provide valuable additional protection, but they are not a universal replacement for CSRF tokens. Applications should evaluate their domain architecture, authentication design, and browser requirements before selecting a defense strategy.
8. How can developers test for CSRF vulnerabilities?
Developers can review state-changing endpoints, test requests without valid tokens, verify Origin and Referer validation, inspect cookie configurations, and use security testing tools to identify weaknesses. Testing should cover every sensitive operation and its authorization requirements.
9. Is CAPTCHA an effective CSRF prevention method?
No. CAPTCHA is primarily intended to distinguish human users from automated activity. It is not a substitute for CSRF tokens, request validation, or appropriate cookie security.
10. Which HTTP methods should be protected against CSRF?
All HTTP methods that change application state, including POST, PUT, PATCH, and DELETE, should be protected appropriately. GET, HEAD, and other safe methods must not perform state-changing operations.
Conclusion: Make CSRF Protection a Core Part of Web Safety
Cross-Site Request Forgery remains an important web application security concern because authenticated browser sessions can be abused when applications fail to validate the legitimacy of state-changing requests.
Ella's banking application illustrates how a seemingly small development oversight can create significant security consequences. A properly implemented CSRF token, supported by secure cookies, origin validation, framework protections, and appropriate authorization controls, can significantly reduce this risk.
For developers, the lesson is straightforward: never assume that a request is legitimate simply because it contains a valid session cookie. Verify the request, validate permissions, and follow secure development practices.
For businesses, CSRF protection should be included in application security reviews, development standards, and regular vulnerability assessments.
Build Safer Web Applications with Kovendo
Understanding cybersecurity vulnerabilities is the first step toward building more secure digital experiences. Explore more practical guides on application security, data privacy, and modern cybersecurity at Kovendo.
Stay informed. Build securely. Protect digital trust.
References and Further Reading
- OWASP: Cross-Site Request Forgery Prevention Cheat Sheet
- OWASP Web Security Testing Guide
- MDN: HTTP Cookies and SameSite Attributes
- Microsoft Learn: Prevent Cross-Site Request Forgery (XSRF/CSRF) Attacks in ASP.NET Core
About the Author: Muhammad Atif is a Digital Technology Strategist specializing in AI, data science, software development, and digital technology. Through Kovendo, he explores practical technology concepts, cybersecurity, and emerging innovations.

Comments
Post a Comment