CSRF
About
Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks an authenticated user into performing unintended actions on a web application without their consent. It exploits the trust a web application has in the user’s browser session.
CSRF and XSRF refer to the same security attack.
CSRF (Cross-Site Request Forgery) → Commonly used term.
XSRF (Cross-Site Request Forgery) → Some security experts and frameworks use this alternative name.
Why Two Names?
"Cross-Site" → "X-Site" abbreviation resulted in XSRF.
Some web frameworks, such as Angular, use XSRF-TOKEN as a CSRF protection mechanism.
How CSRF Works? (Attack Flow)
A typical CSRF attack follows these steps:
User Authentication
A user logs into a web application (e.g., banking website).
The application issues an authentication session (usually via cookies). The browser stores authentication details (like session cookies, JWT, or OAuth tokens)
User Visits a Malicious Site
The user unknowingly visits an attacker-controlled site or clicks a malicious link.
The attacker’s site contains an HTML form or script that sends a request to the victim's application using the authenticated session.
Execution of Unauthorized Action
The victim's browser automatically includes authentication session in the request.
The web application processes the request, assuming it was made by the legitimate user.
Example of a malicious form triggering a CSRF attack:
If the victim is logged in, this request could transfer money without their knowledge.
CSRF vs XSS (Cross-Site Scripting)
Target
Exploits authenticated users
Exploits the application itself
Attack Method
Forces user actions without consent
Injects malicious scripts into web pages
Requires User Authentication?
Yes
No
Mitigation
CSRF tokens, SameSite cookies
Input validation, Content Security Policy (CSP)
Do Browsers Automatically Cascade Session-Related Data?
Yes, browsers automatically include certain session-related data with requests based on security policies and authentication mechanisms. However, not all session-related data is automatically cascaded.
What Session-Related Data Does the Browser Automatically Include?
Type of Authentication
Automatically Sent by Browser?
Reason
Session Cookies
Yes
Cookies are automatically attached to requests based on domain and path rules.
Basic Authentication (Authorization Header: Basic username:password
)
Yes (if cached)
Some browsers remember credentials and resend them.
Bearer Tokens (JWT in Authorization Header)
No
Browsers do NOT automatically attach JWT tokens.
API Keys in Headers
No
API Keys must be explicitly added by the client.
When Does a Browser Automatically Include Session Data?
Cookies (Session-Based Authentication)
Browsers automatically send cookies with every request to the same domain and matching path.
Example: If a user logs into
example.com
, the session cookie is automatically sent with every subsequent request toexample.com/api/*
.
Example: Cookie Auto-Sent by Browser
The browser automatically includes
JSESSIONID
, making it vulnerable to CSRF if not protected.
Basic Authentication (If Cached by the Browser)
If a site uses Basic Authentication, some browsers cache the credentials and resend them automatically.
Example:
However, this behavior depends on browser settings and may not always happen.
Does the Browser Automatically Include JWT Tokens?
No, browsers do NOT automatically attach JWT tokens to requests.
JWTs are stored manually (in
localStorage
,sessionStorage
, or cookies).Unlike cookies, JWTs are not automatically sent unless explicitly added to the
Authorization
header.JWT-based authentication requires the client (JavaScript) to attach the token manually in API requests.
Example: Client Manually Sends JWT in Headers
Since JWTs are explicitly added, CSRF protection is NOT required.
What If a JWT Is Stored in Cookies?
If we store the JWT in a cookie with the HttpOnly
and Secure
flags, the browser will send it automatically like a session cookie.
Example: Storing JWT in a Cookie
If the JWT is stored in a cookie, CSRF protection is needed because the browser will automatically send it with requests/
CSRF Attack Scenarios
1. GET Request-Based CSRF
Many older web applications performed sensitive operations (like fund transfers, account modifications, etc.) using GET requests instead of POST
, PUT
, or DELETE
. Since GET requests are automatically executed by browsers when an image, iframe, or script is loaded, attackers can craft a malicious URL that triggers an action when the victim visits a compromised page.
Example Scenario: Online Banking Fund Transfer
Let’s say an online banking system has an endpoint that allows users to transfer money using a simple GET request:
If a user is logged into their banking account, this request automatically transfers $5000 to the attacker's account when executed.
Attack Execution
Attacker Crafts a Malicious URL
User Visits a Malicious Website
The page automatically loads the
<img>
tag, sending a request to the bank.The request includes the user’s authentication cookies (because it’s an image request to a trusted domain).
Bank Processes the Request
Since the bank’s server sees a legitimate GET request from an authenticated user, it executes the fund transfer.
Mitigation Strategies
Use POST requests for any sensitive actions. GET requests should only retrieve data, never modify it.
Implement CSRF tokens, ensuring that every action requires a unique, server-generated token.
SameSite Cookie Policy, which prevents cookies from being sent with cross-site requests.
2. POST Request-Based CSRF (Form Submission)
Many web applications process sensitive operations using POST requests, but they do not validate the source of these requests.
Attackers can embed hidden forms on malicious sites that auto-submit upon page load, tricking users into performing unintended actions.
Example Scenario: Changing Email Address
Assume a website allows users to change their email address via the following form:
An attacker can create a similar form on their malicious site and auto-submit it when the victim visits.
Attack Execution
Attacker Embeds a Hidden Form on a Malicious Website
User Visits the Malicious Page
The script executes immediately, submitting the form without user interaction.
Server Accepts the Request
Since the user is authenticated, their cookies are automatically sent with the request.
The email gets changed without their knowledge.
Mitigation Strategies
CSRF Tokens: Every form submission must include a unique, server-generated token.
SameSite Cookies: Prevent browsers from sending cookies in cross-site requests.
Referrer Header Validation: Check that the request originated from the same domain.
3. CSRF via AJAX Requests
Modern applications often use AJAX requests to communicate with the server dynamically. If CORS (Cross-Origin Resource Sharing) is misconfigured, an attacker can craft a malicious JavaScript scriptthat triggers API requests from an external site using the victim’s session.
Example Scenario: Unauthorized Money Transfer via Fetch API
A bank provides an API for transferring funds via AJAX:
If the user is authenticated, the browser automatically includes session cookies in the request, making it valid.
Attack Execution
Attacker Hosts Malicious JavaScript
User Visits a Malicious Page
The script executes automatically in the background.
The browser sends a request to
bank.com
with the user’s cookies.
The Bank’s Server Processes the Request
Since the request looks legitimate, the transaction is completed.
Mitigation Strategies
CSRF Tokens: Require a unique token for all AJAX requests.
CORS Configuration: Restrict APIs to trusted domains.
SameSite Cookies: Prevent cookies from being sent with cross-origin requests.
Origin Header Validation: Ensure that requests originate from the same domain.
Mitigation Techniques in Spring Security
Cross-Site Request Forgery (CSRF) is a critical web security vulnerability that allows attackers to trick users into performing unintended actions on authenticated websites. To mitigate CSRF attacks effectively, web applications should implement a combination of the following security measures.
1. CSRF Tokens (Synchronizer Token Pattern)
A CSRF token is a randomly generated unique token that the server generates and associates with a user session. Every sensitive request (e.g., form submission, API call) must include this token. The server validates the token before processing the request.
How CSRF Tokens Work?
Server generates a CSRF token for each user session.
The token is embedded in all forms and AJAX requests.
On submission, the server validates the CSRF token before processing the request.
If the token is missing or invalid, the request is rejected.
Implementation Steps
Default CSRF Configuration (No Need to Manually Enable)
Spring Security enables CSRF protection by default. Any state-changing HTTP requests (POST, PUT, DELETE) require a valid CSRF token.
Generate a CSRF Token
When a user logs in or starts a session, the server generates a unique CSRF token and stores it in the session.
Example in Java (Spring Security):
Embed the CSRF Token in Requests
In HTML forms:
In AJAX requests:
Verify CSRF Token on the Server
When a request is received, the server checks whether the provided token matches the token stored in the session.
Example in Java (Spring Security):
2. SameSite Cookie Attribute
The SameSite attribute in HTTP cookies prevents cookies from being sent with cross-site requests, blocking unauthorized CSRF attempts.
Implementation
When setting cookies, configure the SameSite attribute as Strict
or Lax
:
SameSite Value
Behavior
Example Scenario
Strict
Cookies are sent only for requests from the same site.Cross-site requests won't send cookies.
You are logged into bank.com
. If an attacker tricks you into clicking a malicious link from hacker.com
, your session cookie won't be sent to bank.com
, preventing CSRF.
Lax
Cookies are sent for same-site and top-level GET requests.
You click a link to bank.com
from news.com
. Since it's a top-levelnavigation, cookies are sent. However, cookies are not sent for embedded resources (like images, scripts, or AJAX requests) from other sites.
None
Cookies are sent with all requests, even from different websites, but must be marked as Secure.
If a web app needs cross-site requests (e.g., APIs used by multiple domains), it must use None
and Secure to prevent security risks.
Example in Spring Boot
3. CORS (Cross-Origin Resource Sharing) Restriction
CORS defines which domains are allowed to make requests to a web server. Properly configuring CORS prevents CSRF attacks via AJAX requests.
Implementation
Restrict Allowed Origins
Only allow requests from trusted origins.
Validate Origin and Referer Headers
Ensure that requests originate from an authorized domain.
4. Double Submit Cookie Pattern
The server sets a CSRF token as a cookie.
The frontend reads this cookie and includes it in every request as a header.
The server validates that both values match.
Implementation
Set CSRF Token as a Cookie
Frontend Reads and Includes CSRF Token in Requests
Verify Token on the Server
5. User Authentication-Based Mitigation
Require multi-factor authentication (MFA) for sensitive actions.
Force re-authentication before critical actions like fund transfers.
Example: MFA Prompt
Last updated
Was this helpful?