Application and cloud securityBeginner24 min read

What Is Cross-site request forgery? Security Definition

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security
On This Page

Quick Definition

Cross-site request forgery is a type of attack where a malicious website or email makes your browser perform unwanted actions on another site where you are logged in. For example, clicking a fake link could transfer money from your bank account without you knowing. The attack works because your browser automatically sends your session cookies with every request, making the fake request appear legitimate.

Commonly Confused With

Cross-site request forgeryvsCross-site scripting (XSS)

XSS occurs when a web application sends malicious code (usually JavaScript) to a user’s browser, which then executes it. CSRF, on the other hand, does not involve code execution on the target site; it only involves sending a forged request. XSS can be used to bypass CSRF defenses because the script can read CSRF tokens, but they are fundamentally different vulnerabilities.

In XSS, a hacker stores a script in a blog comment that steals cookies. In CSRF, a hacker puts a hidden form on their own site that transfers money from the victim’s bank account.

Cross-site request forgeryvsSession hijacking

Session hijacking involves an attacker stealing a user’s session ID (e.g., from a cookie or URL) and impersonating them directly. CSRF does not require stealing the session ID; it only requires the user to have an active session. In session hijacking, the attacker uses the session token to authenticate as the user from their own device. In CSRF, the attacker forces the user’s own browser to make requests.

Session hijacking is like stealing someone’s house key and entering their home when they are away. CSRF is like tricking the homeowner into opening the door for a robber while they are already inside.

Cross-site request forgeryvsClickjacking

Clickjacking tricks a user into clicking on something different from what they perceive, by overlaying transparent elements. CSRF tricks the user’s browser into submitting a request, often without any click at all. Clickjacking requires user interaction (a click), whereas CSRF can happen automatically. Both can be prevented with proper frame options (X-Frame-Options) and CSP headers, but CSRF specifically needs tokens or SameSite cookies.

Clickjacking is like putting a fake button on top of a real one so the user clicks the wrong thing. CSRF is like sending a letter from the user's address without the user knowing.

Cross-site request forgeryvsServer-Side Request Forgery (SSRF)

SSRF is an attack where the attacker tricks a server into making requests to internal systems or external resources. In CSRF, the victim is the browser, not the server. SSRF targets the server's internal network, while CSRF targets the user's authenticated sessions. Both are 'forgery' attacks, but they operate at different layers.

SSRF: an attacker sends a URL to a vulnerable web server, which then fetches data from an internal database. CSRF: an attacker tricks a user’s browser into logging the user out of their email.

Must Know for Exams

Cross-site request forgery is an important topic for the CompTIA CySA+ exam, appearing under domain 2 (Software and Systems Security) and domain 3 (Security Operations and Monitoring). Specifically, the exam objectives include the ability to "explain the importance of secure coding practices," "analyze indicators of compromise," and "recommend appropriate mitigation techniques." CSRF is a classic example of a vulnerability that can be detected through secure code review and mitigated with proper coding practices.

In the CySA+ exam, you can expect multiple-choice questions that present a scenario and ask you to identify the vulnerability being exploited, the best defense, or the root cause of a security incident. For example, a question might describe a web application that allows users to transfer money, and logs show transfers originating from IP addresses different from the user’s known IP, but with valid session cookies. The correct answer would identify CSRF as the attack vector, and the recommended fix would be to implement anti-CSRF tokens.

You may also see questions that ask you to distinguish CSRF from similar threats like cross-site scripting (XSS). A common trap is to confuse the two because both involve the user’s browser interacting with a third-party site. The key difference to remember: XSS exploits the user’s trust in a website (the website sends malicious code to the user), while CSRF exploits the website’s trust in the user’s browser (the browser sends forged requests to the website). Questions may present a scenario where an attacker injects a script (that is XSS) versus a scenario where an attacker uses a hidden form on a malicious site (that is CSRF).

The exam also expects you to know the different defense layers: CSRF tokens, SameSite cookies, Referer header validation, and custom headers. You should be able to explain why server-side tokens are more reliable than Referer checking, as some proxies or privacy settings may strip the Referer header. SameSite cookies set to Lax or Strict are increasingly common on the exam due to their adoption in modern browsers.

Finally, the CySA+ exam may include a performance-based question where you are asked to configure a web server or application to mitigate CSRF. Although rare, you might need to select the correct settings in a simulated environment. Familiarize yourself with how to set SameSite cookie attributes in configuration files (e.g., Apache, Nginx, or application code) and how to generate and verify CSRF tokens in common web frameworks like ASP.NET, Django, or Spring.

Simple Meaning

Imagine you are walking through a shopping mall with your house keys in your pocket. You are already inside your house, metaphorically, because you left the front door unlocked while you ran out for a quick errand. Now a stranger sees you leave and slips inside your house. They are not you, but they can use your stuff because the house doesn't check if the person walking in is actually you.

Cross-site request forgery works the same way on the internet. When you log into a website like your bank or email, the website gives your browser a special token called a session cookie. This cookie proves to the website that it is really you making requests. The problem is that your browser automatically sends that cookie with every request to that website, even if the request was triggered by a completely different website.

Now suppose you visit a malicious website while you are still logged into your bank. That malicious site can embed a hidden image or a form that submits a request to your bank’s server, for example, to transfer $500 to the attacker’s account. Because your browser includes your bank’s session cookie automatically, the bank sees a valid request from you and processes it. The attack is called "cross-site" because the request originates from a different site (the attacker’s site) than the target site (the bank). The user never intended to make that request and has no idea it happened until it is too late.

This attack does not require the attacker to steal your password or see your data. It only exploits the fact that your browser holds active authentication credentials for another site. The real danger is that any action you can normally perform on the target website, changing your password, making a purchase, posting a comment, transferring funds, can be forged by an attacker if you are tricked into visiting their malicious page.

Full Technical Definition

Cross-site request forgery, commonly abbreviated as CSRF (often pronounced "sea-surf"), is an attack classified in the OWASP Top 10 as a security misconfiguration and access control vulnerability. It exploits the trust a web application has in a user’s authenticated session by forcing the user’s browser to send unintended HTTP requests to a target site where the user is currently logged in.

The attack relies on the stateless nature of HTTP and the automatic inclusion of cookies by browsers. When a user authenticates to a web application, the server issues a session identifier stored in a cookie. For every subsequent HTTP request to that origin, the browser automatically attaches that cookie, regardless of where the request originated. If an attacker can craft a valid HTTP request that performs a state-changing action (like a POST, PUT, or DELETE), and then embed that request in a page controlled by the attacker, any authenticated user who visits that page will unknowingly trigger the action.

CSRF attacks can be delivered through several mechanisms. The simplest is a hidden HTML form that auto-submits via JavaScript. For example, an attacker might place the following in an HTML page:

<form action="https://bank.com/transfer" method="POST"> <input type="hidden" name="toAccount" value="attackerAccount"> <input type="hidden" name="amount" value="1000"> <input type="submit" value="Click here to claim your prize"> </form> <script>document.forms[0].submit();</script>

When a user who is logged into bank.com loads this attacker’s page, the browser submits the form, sending the user’s session cookie along with the request. The bank’s server validates the cookie and processes the transfer.

Another common vector is the use of image tags, which are allowed by the same-origin policy to make GET requests across origins. An attacker can embed an image like <img src="https://bank.com/transfer?to=attacker&amount=1000" />, and the browser will load that URL, sending the session cookie. If the bank’s API accepts GET requests for sensitive actions, the attack succeeds.

Modern frameworks implement CSRF tokens to mitigate this threat. A CSRF token is a unique, unpredictable value generated by the server and embedded in forms or added as a custom header (e.g., X-CSRF-Token). The server verifies this token on every state-changing request. Because the attacker cannot predict or read the token value (due to same-origin policy), they cannot craft a valid forged request. SameSite cookies, introduced in RFC 6265bis, also help by instructing the browser to withhold cookies for cross-site requests. Setting the SameSite attribute to Lax or Strict prevents the browser from sending cookies when the request originates from a different site, effectively blocking CSRF for most GET-based attacks.

Other defenses include checking the Referer or Origin header, requiring reauthentication for sensitive actions, and using custom request headers that cannot be set cross-origin. In enterprise environments, Web Application Firewalls (WAFs) can also detect and block CSRF attempts by inspecting request patterns.

For the CySA+ exam, you should understand that CSRF targets authenticated sessions, not stolen credentials. The primary defense is the use of anti-CSRF tokens. Knowing the difference between CSRF and XSS is critical: XSS exploits the user’s trust in a website, while CSRF exploits the website’s trust in the user’s browser.

Real-Life Example

Think of CSRF like a forged signature on a check. Imagine you are at a coffee shop. You already wrote a blank check to the coffee shop and left it with the barista so you can quickly pay each time you order, this is like your browser keeping an active session cookie. Now a stranger walks up to the barista and hands them a piece of paper that says "Pay this stranger $100 from my account." The barista looks at the paper and sees your signature at the bottom. But the signature is fake, the stranger traced it from a receipt you threw away. Because the barista trusts the signature and doesn't check if you are actually standing there, they process the payment.

In this analogy, your signature is the session cookie. The barista is the bank’s webserver. The stranger is the attacker. The fake piece of paper is the forged HTTP request. The coffee shop does not verify that you actually intended to authorize that transfer, they just see the signature and assume it is genuine. The same thing happens with CSRF: the server sees a valid session cookie and assumes the request came from you, when in reality it came from a malicious site you visited.

Now let’s say you are still logged into your email account while browsing a forum. An attacker posts a comment with a hidden link that says "Click for funny cat videos." When you click it, your browser sends a request to your email provider’s "delete all emails" endpoint, using your active session. The email provider sees the request has your valid cookie, so it deletes all your emails. You never wanted that, but the browser acted on the attacker’s behalf.

CSRF is particularly dangerous because you don’t need to be tricked into entering your password again. You just need to be authenticated on the target site and then visit a malicious page. That is why security professionals emphasize the importance of CSRF tokens and SameSite cookie attributes.

Why This Term Matters

Cross-site request forgery matters in real-world IT because it directly undermines the trust model of web applications. Since the attack does not require the attacker to steal passwords or exploit software bugs, it can be carried out even against well-coded websites that simply lack CSRF protection. For organizations that handle sensitive user actions, banks, healthcare portals, cloud management consoles, e-commerce platforms, a single CSRF vulnerability can lead to unauthorized fund transfers, data changes, account takeovers, or privilege escalations.

From a practical IT perspective, CSRF is a serious concern for both developers and security analysts. Developers must implement CSRF tokens in all state-changing endpoints. Security analysts must know how to test for CSRF vulnerabilities in web applications during penetration tests and code reviews. If a CSRF flaw is found, the remediation is usually straightforward but critical: add anti-CSRF tokens and verify SameSite cookie settings.

In enterprise environments, CSRF can bypass other security controls. For example, if an organisation uses single sign-on (SSO), a user might be logged into many different applications at once. An attacker could potentially forge requests across all those applications if only one of them is vulnerable. This makes CSRF a cross-application attack surface that cannot be ignored.

the rise of RESTful APIs and single-page applications (SPAs) has introduced new challenges. SPAs often rely on token-based authentication (like JWT) stored in localStorage or cookies. If the token is in a cookie without SameSite protection, CSRF can still occur. If the token is in localStorage, CSRF is not directly possible because browser requests do not automatically include localStorage values, but then XSS becomes a concern. The trade-offs between security mechanisms are a central topic in modern web security.

For IT professionals studying for the CompTIA CySA+ exam, understanding CSRF is essential because the exam tests your ability to identify and mitigate web application vulnerabilities. You may be presented with a log file or a web app configuration and asked to recognize signs of a CSRF attack or recommend the appropriate countermeasure.

How It Appears in Exam Questions

CSRF questions in the CySA+ exam typically follow one of several patterns. The most common is a scenario-based question that describes an incident: "A company notices that several users have had their account settings changed without their knowledge. The changes originated from IP addresses not associated with the users. Which type of attack is most likely occurring?" The correct answer is CSRF. The distractors often include XSS, SQL injection, and session hijacking. To answer correctly, you must recognize that the attack does not involve stolen credentials or malicious scripts running on the vulnerable site, it involves forged requests from an external site.

Another pattern is a configuration-based question: "A web developer wants to prevent CSRF attacks. Which of the following is the most effective mitigation technique?" Options might include input validation, output encoding, SQL parameterization, and CSRF tokens. Input validation and output encoding are defenses against injection and XSS, while SQL parameterization prevents SQL injection. The correct answer is CSRF tokens. You will also see options like "Using HTTPS" or "Setting Secure flag on cookies", these protect against eavesdropping, not CSRF.

A third pattern involves log analysis. The exam might present log entries showing HTTP requests with unusual Referer headers or missing CSRF tokens. For example, a log entry shows a POST request to /transfer-funds with a valid session cookie but a Referer header pointing to www.attacker-site.com. The question might ask: "Which indicator in the logs suggests a CSRF attack?" The answer is the mismatch between the Referer and the legitimate site.

You may also encounter a question that tests your understanding of SameSite cookies. The question might say: "A security analyst recommends setting the SameSite attribute to Lax on session cookies. Which type of attack does this primarily mitigate?" The answer is CSRF. You should know that Lax allows cookies on top-level navigations (e.g., clicking a link) but blocks them on subresource requests like form submissions from other sites.

Finally, there are troubleshooting questions: "After implementing anti-CSRF tokens, users report that they cannot submit forms on the website. What is the most likely cause?" Possible answers include the token being expired, the token not being sent with the request, or the token validation logic being incorrectly implemented. The correct answer is usually that the token was missing or not regenerated correctly.

Practise Cross-site request forgery Questions

Test your understanding with exam-style practice questions.

Practise

Example Scenario

The Acme Corporation hosts an internal web application for expense approvals. Employees log in using their corporate credentials, and the application stores a session cookie in their browser. The application allows managers to approve or reject expense reports by clicking a button. The URL for approving an expense report is https://expenses.acme.com/approve?id=12345.

One day, a security analyst named Priya notices that several expense reports for large amounts have been approved without the managers remembering doing so. She investigates the server logs and finds that each approval request came from a session belonging to the respective manager, but the Referer header pointed to a website called http://cute-cats.info. Priya immediately suspects a CSRF attack.

Further analysis reveals that an attacker sent a phishing email to several managers with a link to http://cute-cats.info, which displayed a harmless-looking cat video. On that page, the attacker embedded an invisible image tag: <img src="https://expenses.acme.com/approve?id=12345" width="0" height="0" />. When the managers visited the malicious site while still logged into the expense system, their browsers automatically made a GET request to the approve endpoint, using their valid session cookies. The server, lacking any CSRF protection, accepted the requests and approved the fraudulent expense reports.

Priya also notices that the approve endpoint uses a GET request for a state-changing action, a major security red flag. The fix requires two changes: first, change the approve endpoint to require a POST request. Second, implement a CSRF token that is generated per session and included as a hidden field in the approval form. The server then verifies the token before processing the request. After these changes, any attempt to forge a request from another site will fail because the attacker cannot guess the token.

This scenario illustrates how CSRF can be executed silently, without the user ever clicking a button on the vulnerable site. The user only had to visit a malicious page while authenticated. For the CySA+ exam, remember that GET requests should never perform state changes, and CSRF tokens are the standard defense.

Common Mistakes

Thinking CSRF requires the user to click a button on the vulnerable site.

CSRF can be triggered automatically by the browser loading an image, script, or iframe, or by auto-submitting a form using JavaScript. The user may not even interact with the vulnerable site at all.

Assume any cross-origin request can be automated. Always use anti-CSRF tokens for all state-changing endpoints, even if the user does not interact directly.

Confusing CSRF with cross-site scripting (XSS).

XSS involves injecting malicious scripts into a trusted website, while CSRF involves forging requests from an untrusted website. They exploit different trust relationships.

Remember: XSS is about code execution on a trusted site, CSRF is about request forgery from an untrusted site. XSS can sometimes be used to bypass CSRF protections, but they are distinct vulnerabilities.

Believing that HTTPS alone prevents CSRF.

HTTPS encrypts data in transit but does not verify the origin or intent of a request. An attacker can still craft a valid HTTPS request if the user’s browser holds the session cookie.

HTTPS is essential for confidentiality, but it does not prevent CSRF. You must implement CSRF-specific defenses such as tokens or SameSite cookies.

Assuming a CSRF token stored in a cookie prevents attacks.

If the CSRF token itself is stored in a cookie and the server only checks that cookie, then any cross-site request will still include the cookie. The attacker's request can include the token.

The CSRF token must be sent in a non-cookie location, such as a request header or a hidden form field, and compared to a server-side value (often stored in the session). The classic double-submit cookie pattern is considered less secure.

Thinking that using POST instead of GET fully prevents CSRF.

While GET requests are easier to exploit with image tags, an attacker can still craft a POST request using a form with hidden fields and auto-submit it with JavaScript.

Using POST reduces the attack surface but does not eliminate CSRF. You still need CSRF tokens or other server-side verification.

Exam Trap — Don't Get Fooled

{"trap":"A question states: 'A web application uses session cookies to authenticate users. The developer implements input validation on all forms. Which vulnerability is still present?'

Many learners choose 'SQL injection' or 'XSS' because they assume input validation covers everything. However, input validation does not prevent CSRF.","why_learners_choose_it":"Learners often think that input validation is a catch-all security measure.

They also confuse CSRF with injection attacks. Since CSRF does not involve malicious input submitted to the application, input validation offers no protection.","how_to_avoid_it":"Memorize that CSRF is not a form of input injection.

It is an access control issue. Always look for the presence or absence of anti-CSRF tokens when analyzing a web application’s security posture."

Step-by-Step Breakdown

1

User authenticates to a target website

The user logs into a website (e.g., their online banking portal). The server creates a session and sends a session cookie to the user’s browser. The browser stores this cookie and will automatically attach it to all future requests to that site.

2

User visits a malicious website while still authenticated

Without logging out of the banking site, the user navigates to a different website controlled by an attacker. This could be a forum, a link in a phishing email, or an ad network. The malicious site is designed to exploit the user’s active session.

3

Malicious site triggers a cross-origin request to the target site

The attacker’s page contains HTML or JavaScript that automatically sends an HTTP request to the target site (e.g., a POST form or an image tag). The request is crafted to perform a specific action, such as transferring money, changing an email address, or deleting data.

4

Browser automatically includes the session cookie

Because the request is sent to the target site’s origin, the browser automatically attaches the valid session cookie. The server receives the request with a seemingly legitimate authentication token. It does not check where the request originated from.

5

Target server processes the request as genuine

The server sees the valid session cookie and processes the state-changing action. The action is executed, often without any visual feedback to the user. The attacker achieves their goal without the user’s knowledge or consent.

6

Mitigation: Anti-CSRF token validation

If the target site were protected, the server would embed a unique CSRF token in every form or request header. The attacker’s page would not be able to know this token (due to same-origin policy). The server would then reject requests without a valid token, stopping the attack.

Practical Mini-Lesson

Cross-site request forgery is a vulnerability that every web developer and security professional must understand because it directly exploits the browser’s automatic credential management. In practice, the most common reason CSRF exists is that developers forget to protect state-changing endpoints. They might use GET for convenience or rely on the same-origin policy for protection, not realizing that forms and images can still cross origins.

When you are building or reviewing a web application, you must identify every endpoint that changes server-side state. This includes anything that writes to a database: creating, updating, deleting records, changing user settings, placing orders, sending messages. Each of these endpoints must require a CSRF token. The token is typically generated by the server and stored in the session. It is then included in the HTML form as a hidden input or sent as a custom header (e.g., X-CSRF-Token) for AJAX requests. The server compares the submitted token with the stored value. If they match, the request is allowed.

In modern web frameworks, CSRF protection is often built in. For example, Django, Ruby on Rails, Spring Security, and ASP.NET Core all have built-in CSRF token middleware. However, developers can accidentally disable it or forget to include the token in forms. As a security analyst, you should check for the presence of these tokens during code reviews. Look for forms that lack a hidden field like __RequestVerificationToken or csrfmiddlewaretoken.

Another practical consideration is the use of SameSite cookies. Setting the SameSite attribute to Lax or Strict can prevent the browser from sending cookies on cross-site requests. This is a robust defense for many CSRF scenarios, but it has limitations. For example, SameSite=Strict may break legitimate cross-site integration like payment gateways. The exam expects you to know that SameSite is a complementary defense, not a replacement for CSRF tokens.

What can go wrong? If you use a double-submit cookie pattern (where the CSRF token is stored in a cookie as well as in a request parameter), an attacker who can set cookies on the target domain (e.g., via a subdomain vulnerability) can bypass CSRF protections. Also, if you use a weak token generation algorithm (like predictable random values), an attacker could guess the token. In real-world pen tests, assessors often try to bypass CSRF protections by exploiting XSS, checking if the token is predictable, or testing if the token is not validated for certain HTTP methods.

Finally, always remember that CSRF tokens must be unique per session or per request. They must be unpredictable and tied to the user’s session. Storing the token in a cookie alone is insufficient. The correct implementation is to store the token server-side and compare it against a client-supplied value that does not come from a cookie.

Memory Tip

Remember CSRF as 'Sea Surf', the attacker surfs on top of your session cookie. The website trusts the cookie, not the user’s intent.

Covered in These Exams

Current Exam Context

Current exam versions that test this topic — use these objectives when studying.

Related Glossary Terms

Frequently Asked Questions

Can CSRF be prevented by using HTTPS?

No. HTTPS encrypts the data in transit but does not prevent the browser from sending the session cookie with the forged request. CSRF tokens or SameSite cookies are required.

Is CSRF the same as session hijacking?

No. Session hijacking involves an attacker stealing a session ID and using it directly. CSRF does not require the attacker to ever know the session ID; it only requires the victim’s browser to send it automatically.

Does disabling JavaScript prevent CSRF?

Not entirely. While JavaScript can automate form submissions, an attacker can use an HTML form with a submit button and social engineering to get the user to click it. However, most automatic CSRF attacks rely on JavaScript.

What is a CSRF token used for?

A CSRF token is a unique, unpredictable value generated by the server and included in forms or headers. The server verifies the token on every state-changing request to ensure the request originated from the same site, not a cross-site forgery.

Can SameSite cookies completely replace CSRF tokens?

Not yet. While SameSite cookies provide strong protection, they are not supported by all browsers (very old ones). Also, they can be bypassed in some edge cases, like using subdomain attacks. The recommended approach is to use both SameSite cookies and CSRF tokens.

How do I test for CSRF vulnerabilities?

You can test by intercepting a legitimate request (like a form submission) using a proxy like Burp Suite. Remove the CSRF token from the request and see if the server still accepts it. If it does, the endpoint is vulnerable. Alternatively, try submitting the request from a different origin using a simple HTML page.

Summary

Cross-site request forgery is a web security vulnerability that exploits the trust a website places in a user’s browser. The attacker does not need to steal passwords or inject code; they only need to trick an authenticated user into visiting a malicious page. From that page, the user’s browser automatically sends a forged request with valid session cookies, causing the target website to perform an action the user never intended. This can include transferring money, changing passwords, or deleting data.

For IT professionals, CSRF is a critical concept because it appears in secure coding standards, penetration testing methodologies, and security frameworks like OWASP. Defenses include anti-CSRF tokens, SameSite cookies, and careful design of state-changing API endpoints. The vulnerability is simple to exploit but equally simple to prevent with proper implementation.

For the CySA+ exam, you need to be able to identify CSRF in scenarios, distinguish it from XSS and other attacks, and recommend the correct mitigation. Remember that CSRF is about request forgery, not code injection. A memory hook: "CSRF = session surfing." The site trusts the cookie, not the user’s actual intent. Always verify that state-changing actions are protected by tokens from the server side.