Web applications often rely on browser sessions and cookies to identify authenticated users. Once a user logs in, the browser automatically sends the relevant session cookie with requests to that website. This behavior makes web applications convenient, but it can also create an important security risk.
Cross-Site Request Forgery (CSRF) is a web security vulnerability that allows an attacker to trick an authenticated user’s browser into sending an unwanted request to a trusted application. If the application does not properly verify that the request was intentionally made by the user, the action may be accepted.
A CSRF attack does not normally require the attacker to steal the victim’s password or session cookie. Instead, the attacker abuses the browser’s existing authenticated state. Depending on the victim’s permissions, the impact can range from changing account information to performing financial or administrative actions.
CSRF remains an important topic in web application penetration testing because authentication alone does not prove that a particular request was intentionally initiated by the user.
What Is Cross-Site Request Forgery (CSRF)?
Cross-Site Request Forgery is an attack where a malicious website, page, email, or other attacker-controlled content causes a victim’s browser to make an unintended request to another website where the victim is already authenticated.
Consider a simple account management application:
User logs in
↓
Session cookie is created
↓
Browser stores the cookie
↓
User visits another website
↓
Malicious page causes a request to the trusted application
↓
Browser may automatically include the session cookie
If the target application does not have an appropriate CSRF defense, it may process the request as if the user intentionally performed the action.
OWASP describes CSRF as an attack that forces an authenticated end user to execute unwanted actions on a web application. The potential impact depends on the privileges of the victim and the functionality exposed by the application.
Why Is CSRF Important?
CSRF can become serious when an application performs sensitive actions based primarily on the user’s authenticated session.
Potentially affected actions include:
- Changing an email address
- Changing account settings
- Updating a password
- Adding an account beneficiary
- Making a purchase
- Submitting a transaction
- Changing security preferences
- Performing administrative actions
- Modifying user permissions
The severity depends on the endpoint and the victim’s privileges.
A CSRF vulnerability affecting a normal profile update may have limited impact. The same weakness affecting an administrator’s account could potentially have much greater consequences.
How Does a CSRF Attack Work?
To understand CSRF, it helps to understand how normal authenticated requests work.
Suppose a user is logged into:
https://example.com
The browser has a session cookie:
Cookie: session=USER_SESSION_VALUE
The user then sends a legitimate request:
POST /account/email
Content-Type: application/x-www-form-urlencoded
Cookie: session=USER_SESSION_VALUE
email=user@example.com
The server identifies the session and processes the request.
Now imagine the user visits an attacker-controlled website.
That website attempts to cause the browser to submit a request to the trusted application.
If the browser includes the user’s authentication credentials and the application does not require additional proof that the request originated from the legitimate application, the request may be accepted.
The attacker does not necessarily need to know the session cookie.
The browser may send it automatically.
A Simple CSRF Example
Imagine an application allows users to change their email address through:
POST /change-email
The legitimate request might contain:
email=newaddress@example.com
A vulnerable application may only check whether the user is authenticated.
An attacker could create a malicious page designed to cause the victim’s browser to submit a request to the target application.
The important point is that the attacker is not directly making the authenticated request from their own computer.
The victim’s browser is making the request.
That distinction is what makes CSRF possible.
CSRF Attack Flow
A typical CSRF scenario can be represented as:
Victim
│
│ Logged in
▼
┌───────────────┐
│ Trusted Site │
└───────────────┘
│
Session Cookie
│
▼
┌───────────────┐
│ Victim Browser│
└───────────────┘
▲
│
Malicious Website
│
Forged Request
│
▼
┌───────────────┐
│ Trusted Site │
└───────────────┘
The browser sits between the attacker-controlled content and the trusted application.
The attacker attempts to abuse the browser’s authenticated state.
Types of CSRF Attacks
CSRF is not limited to one particular request format.
GET-Based CSRF
A vulnerable application may incorrectly use a GET request for a state-changing operation.
For example:
GET /delete-account?id=123
Changing or deleting server-side data through GET is poor application design.
If such an endpoint exists, an attacker may attempt to cause the victim’s browser to visit the URL.
State-changing actions should generally use appropriate HTTP methods and require proper CSRF protection.
POST-Based CSRF
POST requests can also be vulnerable.
A common attack scenario involves an HTML form that causes the victim’s browser to submit data to the target application.
The key issue is not whether the request uses GET or POST.
The real question is whether the server can distinguish a legitimate request from a forged one.
Login CSRF
CSRF can also affect login workflows.
In a login CSRF scenario, an attacker attempts to cause the victim to become authenticated as an account controlled by the attacker.
This can create unexpected consequences when the victim later enters sensitive information into the account they believe belongs to them.
Login functionality therefore deserves CSRF testing just like other sensitive workflows.
API and AJAX-Based CSRF
Modern applications frequently use JavaScript and APIs rather than traditional HTML forms.
Applications using cookie-based authentication can still require CSRF protection for state-changing API requests.
Custom headers and CSRF tokens are commonly used to help distinguish legitimate requests from cross-site requests.
CSRF vs XSS
CSRF and Cross-Site Scripting are often confused because both involve attacks against web applications.
They are different vulnerabilities.
CSRF
The attacker tricks a victim’s browser into performing an action on a trusted website.
XSS
The attacker causes malicious script content to execute in the context of a trusted website.
A useful distinction is:
CSRF → Tricks the browser into making a request
XSS → Executes attacker-controlled script in the target context
There is also an important relationship between them.
A serious XSS vulnerability can undermine many CSRF defenses because malicious script running in the application’s origin may be able to interact with the application’s legitimate functionality.
This is why CSRF protection should be considered part of a broader web application security strategy.
CSRF Tokens
One of the most common defenses against CSRF is a CSRF token.
A CSRF token is a value that the server generates and expects the client to submit with state-changing requests.
For example:
POST /transfer
The request might contain:
amount=1000
csrf_token=RANDOM_UNPREDICTABLE_VALUE
The server verifies that the token is valid before processing the request.
An attacker may be able to cause the browser to send the request, but if they cannot obtain the legitimate CSRF token, they cannot construct a valid request.
A good CSRF token should be:
- Unpredictable
- Secret
- Sufficiently random
- Associated with the user’s session or request
- Validated server-side
Synchronizer Token Pattern
The synchronizer token pattern stores the CSRF token on the server, commonly alongside the user’s session.
A simplified flow looks like:
User requests page
↓
Server generates token
↓
Token included in page
↓
User submits request
↓
Server compares token
↓
Valid → Process
Invalid → Reject
This is one of the established approaches for applications using cookie-based authentication.
Applications should avoid implementing their own cryptographic mechanisms unnecessarily. Modern frameworks often provide built-in CSRF protection that should be used where appropriate.
Double-Submit Cookie Pattern
Another approach is the double-submit cookie pattern.
The general idea is that a token is provided through a cookie and must also appear in the request.
The server verifies that the expected values match.
However, implementations matter.
A naive double-submit design can have weaknesses if an attacker can inject or overwrite cookies. A signed and properly bound implementation provides stronger protection.
Developers should follow established framework and security guidance rather than creating an ad-hoc token system.
SameSite Cookies
The SameSite cookie attribute provides another layer of protection.
Common values include:
SameSite=Strict
SameSite=Lax
SameSite=None
SameSite=Strict
The browser applies stricter cross-site cookie rules.
This can provide strong CSRF resistance but may affect certain legitimate cross-site workflows.
SameSite=Lax
This provides a balance between usability and security and is widely used for session cookies.
However, it should not automatically be considered a complete CSRF defense.
SameSite=None
This permits cross-site cookie usage and must be combined with Secure.
Applications using SameSite=None should pay particular attention to their CSRF architecture.
SameSite should generally be treated as an additional layer rather than assuming it solves every CSRF scenario.
Origin and Referer Validation
Servers can also inspect browser-supplied headers such as:
Origin: https://example.com
or:
Referer: https://example.com/account
The application can compare the expected origin with the origin associated with the request.
This can provide useful additional protection for sensitive state-changing operations.
Header validation should be implemented carefully because legitimate requests can have different header behaviors depending on browser, privacy settings, redirects, and application architecture.
How to Test for CSRF Vulnerabilities
CSRF testing should always be performed against applications you are authorized to test.
A penetration tester typically starts by identifying state-changing functionality.
Examples include:
- Profile updates
- Password changes
- Email changes
- Payment actions
- Account settings
- User management
- Administrative functions
Step 1: Identify State-Changing Requests
Use the application normally and capture requests through a proxy such as Burp Suite.
Look for:
POST
PUT
PATCH
DELETE
Also investigate GET requests that unexpectedly modify server-side state.
Step 2: Check for CSRF Protection
Inspect the request for indicators such as:
csrf_token
_csrf
X-CSRF-Token
X-XSRF-Token
The exact parameter or header depends on the framework and implementation.
Step 3: Remove the Token
In an authorized test environment, remove or modify the CSRF token and resend the request.
A secure application should reject the request or otherwise prevent the sensitive action.
Step 4: Test Token Validation
A tester can determine whether:
- Missing tokens are rejected
- Invalid tokens are rejected
- Expired tokens are rejected when applicable
- Tokens are properly associated with the session
- Tokens can be reused
- Tokens are predictable
Testing should focus on the actual security boundary rather than simply checking whether a parameter named csrf_token exists.
Step 5: Test Sensitive Workflows
Prioritize high-impact functionality.
For example:
Change Email
Change Password
Add Payment Method
Transfer Funds
Change User Role
Delete Account
A CSRF weakness on a harmless preference may have low severity, while the same issue on a financial transaction can be critical.
Testing CSRF With Burp Suite
“https://portswigger.net/burp” Burp Suite is commonly used for authorized web application testing.
A tester can intercept a legitimate request and send it to Repeater for controlled analysis.
For example:
Normal Request
↓
Capture in Burp
↓
Identify CSRF controls
↓
Modify/remove token
↓
Replay request
↓
Observe response and state change
The tester should verify the actual effect of the request.
A server returning HTTP 200 OK does not necessarily mean the operation succeeded. Conversely, an error response may still have caused a partial state change.
This is why CSRF testing should combine HTTP-level analysis with application-level verification.
How Developers Can Prevent CSRF
A strong CSRF defense uses multiple layers.
Use Framework Protection
Many modern web frameworks provide built-in CSRF protection.
Use the framework’s established mechanism rather than creating a custom solution unless there is a specific architectural reason.
Protect State-Changing Requests
CSRF protection should cover operations that change application state.
Examples include:
- POST
- PUT
- PATCH
- DELETE
If a GET endpoint changes state, redesigning the endpoint is usually preferable to trying to compensate for the unsafe design.
Use Secure, Unpredictable Tokens
CSRF tokens should be generated using a secure random mechanism and validated server-side.
Do not use predictable values such as:
123456
username
email address
timestamp
Configure Cookies Correctly
Session cookies should use appropriate security attributes such as:
Secure
HttpOnly
SameSite
The correct configuration depends on the application’s architecture and cross-site requirements.
Validate Origins for Sensitive Operations
For particularly sensitive applications, Origin or Referer validation can provide another useful security layer.
Require Reauthentication for Critical Actions
High-risk operations may require additional user interaction.
For example:
Change Password
↓
Re-enter Password
↓
Confirm Action
Financial applications may use stronger transaction confirmation mechanisms.
This does not replace general CSRF protection, but it can reduce the impact of attacks against highly sensitive operations.
Common CSRF Prevention Mistakes
Several implementation mistakes appear repeatedly during security assessments.
Relying Only on SameSite Cookies
SameSite is useful, but application architecture matters.
Do not assume that setting a cookie attribute automatically eliminates every CSRF risk.
Protecting Only Some Endpoints
A common mistake is protecting the profile update endpoint while leaving another state-changing endpoint unprotected.
Security controls should be applied consistently.
Accepting GET Requests for State Changes
Endpoints such as:
GET /delete
GET /change-email
GET /transfer
should raise immediate security concerns.
GET should normally be safe and idempotent rather than used to perform sensitive state changes.
Checking Only for Token Presence
An application that checks:
if csrf_token exists
without verifying whether it is valid provides little meaningful protection.
The server must validate the token correctly.
Exposing Tokens in Unsafe Places
CSRF tokens should not unnecessarily appear in URLs because URLs may be stored in browser history, logs, analytics systems, or other locations.
CSRF Prevention Best Practices
Organizations can use the following checklist when reviewing applications:
- Use framework-provided CSRF protection.
- Protect all relevant state-changing operations.
- Generate unpredictable CSRF tokens.
- Validate tokens server-side.
- Associate tokens with the appropriate session or security context.
- Configure session cookies with appropriate
Secure,HttpOnly, andSameSiteattributes. - Avoid state-changing GET requests.
- Validate Origin or Referer where appropriate.
- Use stronger confirmation for highly sensitive operations.
- Test CSRF protections during VAPT.
- Keep web frameworks and security libraries updated.
- Treat XSS prevention as a complementary security requirement.
- Monitor unusual account and transaction activity.
For organizations looking to strengthen their broader security posture, “https://pentesthint.com/” security consulting and structured application security assessments can help identify weaknesses that are difficult to discover through automated scanning alone.
CSRF in APIs and Modern Web Applications
Modern applications increasingly use REST APIs, SPAs, and JavaScript-heavy interfaces.
This changes how CSRF needs to be evaluated.
For example, an API might use:
POST /api/account/update
Cookie: session=...
Content-Type: application/json
If the API relies on cookies for authentication, CSRF remains relevant.
Applications can use techniques such as:
- CSRF tokens
- Custom request headers
- Strict CORS policies
- SameSite cookies
- Origin validation
A custom header can be particularly useful because browsers restrict cross-origin sites from freely creating requests with arbitrary custom headers without the appropriate CORS preflight.
However, CORS configuration must also be reviewed carefully. An overly permissive credentialed CORS policy can undermine security assumptions.
CSRF and CORS Are Not the Same
CSRF and CORS address different problems.
CSRF concerns whether an attacker can cause a browser to perform an unwanted authenticated action.
CORS controls whether browser-based JavaScript can make certain cross-origin requests and access their responses.
A permissive CORS policy does not automatically mean an application is vulnerable to CSRF, and a restrictive CORS policy does not automatically replace CSRF protection.
They should be analyzed separately as part of the application’s overall security model.
CSRF in VAPT and Penetration Testing
CSRF testing should be included when assessing applications that rely on browser sessions or other automatically attached credentials.
During a professional VAPT engagement, testers should prioritize:
- Authentication workflows
- Account management
- Financial transactions
- Password changes
- Email changes
- Privilege management
- Administrative functions
- API endpoints using cookies
- Sensitive user actions
The final report should explain both the technical weakness and its business impact.
For example, instead of simply reporting:
“CSRF token missing.”
A stronger finding would explain:
“The account email-change endpoint does not require a valid CSRF token, allowing an attacker to potentially cause an authenticated victim to submit an unintended email change.”
This makes the finding easier for developers and business teams to understand and remediate.
Learning CSRF Through Practical Labs
CSRF is much easier to understand when you can observe the complete request lifecycle.
A beginner can start by learning:
HTTP Requests
↓
Cookies
↓
Sessions
↓
Authentication
↓
State-Changing Requests
↓
CSRF Tokens
↓
CSRF Testing
Those building practical skills can use “https://vuln.pentesthint.com/” cyber security labs to practice against intentionally vulnerable applications in a controlled environment.
For structured “https://academy.pentesthint.com/” cyber security training, combining HTTP fundamentals with hands-on web security testing provides a stronger foundation than memorizing vulnerability definitions alone.
Frequently Asked Questions
What is Cross-Site Request Forgery (CSRF)?
Cross-Site Request Forgery is a web security vulnerability where an attacker tricks an authenticated user’s browser into sending an unwanted request to a trusted application.
How does a CSRF attack work?
The attacker causes the victim’s browser to send a request to a website where the victim is already authenticated. If the application relies only on automatically submitted authentication credentials and lacks appropriate CSRF defenses, it may process the forged request.
What is a CSRF token?
A CSRF token is an unpredictable value used to verify that a state-changing request originated from an authorized application context rather than an attacker-controlled site.
Is CSRF still relevant with SameSite cookies?
Yes. SameSite cookies provide valuable protection, but they should not automatically be treated as a complete replacement for CSRF defenses. The correct approach depends on the application’s authentication model, browser compatibility requirements, domain structure, and sensitive workflows.
Can CSRF steal passwords?
CSRF itself generally does not directly steal passwords. It abuses an authenticated browser session to perform actions. However, the vulnerability can sometimes be chained with other weaknesses or affect sensitive account operations.
Is CSRF possible in REST APIs?
Yes, particularly when the API uses browser-managed cookies or other credentials that browsers automatically attach to requests. APIs using different authentication architectures may have a different CSRF threat model.
How do you test CSRF vulnerabilities?
Authorized testers typically identify state-changing requests, inspect CSRF protections, remove or modify tokens, test validation behavior, and verify whether an unauthorized cross-site request can cause a meaningful state change.
Is CSRF the same as XSS?
No. CSRF tricks a browser into performing an unwanted action, while XSS involves executing attacker-controlled script in the context of a vulnerable application. XSS can, however, undermine some CSRF defenses.
Conclusion
Cross-Site Request Forgery remains an important web application security issue because browsers are designed to automatically handle authentication credentials such as cookies.
That convenience creates a security challenge: the server needs a way to determine whether a sensitive request was intentionally generated by the application or was triggered through an attacker-controlled context.
CSRF tokens remain one of the most established defenses for applications that rely on cookie-based authentication. SameSite cookies, Origin validation, appropriate CORS configuration, secure session management, and additional confirmation for high-risk operations can provide further layers of protection.
For penetration testers, CSRF testing should go beyond looking for a parameter named csrf_token. The important questions are whether the protection is actually validated, whether every sensitive endpoint is covered, and whether an attacker can cause a meaningful state change.
For developers, the safest approach is to use established framework protections, avoid state-changing GET requests, enforce security controls server-side, configure cookies correctly, and test critical workflows regularly.
If you want to develop practical web application security skills, explore “https://pentesthint.com/” PentestHint, practice with “https://vuln.pentesthint.com/” hands-on labs, and build a strong foundation through “https://academy.pentesthint.com/” practical cyber security learning.
Understanding CSRF is not just about learning another vulnerability. It is about understanding how browsers, authentication, HTTP requests, sessions, and application workflows interact—and how attackers can abuse that interaction when security controls are missing.
