Understanding CSRF Attacks and Prevention Strategies in Front-End Development
CSRF attacks trick a logged‑in user’s browser into sending authenticated requests to a target site, enabling unauthorized actions, so front‑end developers must mitigate them by enforcing same‑origin checks, using anti‑CSRF tokens or double‑cookie verification, and configuring SameSite cookie attributes to block cross‑site requests.
With the rapid development of the Internet, information security has become a top concern for enterprises, and the front‑end is a high‑risk point for security incidents. In the mobile‑Internet era, front‑end developers face traditional threats such as XSS and CSRF, as well as newer issues like network hijacking and illegal Hybrid API calls. Although browsers have introduced security mechanisms such as CSP and Same‑Site Cookies, many vulnerabilities still exist and require continuous “gap‑filling”.
Background
CSRF (Cross‑Site Request Forgery) is an attack where the attacker tricks a victim into sending a request to a target site while the victim’s authentication credentials (cookies, tokens) are automatically attached. The attacker then performs actions on behalf of the victim.
CSRF Attack Flow
The victim logs into a.com and retains authentication cookies.
The attacker lures the victim to visit b.com. b.com sends a request to a.com/act=xx; the browser automatically includes the victim’s cookies. a.com validates the request, assumes it comes from the victim, and executes the action.
Real‑World Example
A classic Gmail CSRF case (2007) involved a hidden form that automatically created a mail filter forwarding all incoming mail to [email protected]. The attacker leveraged the victim’s logged‑in Gmail session, so the request carried the victim’s cookies and succeeded.
<form method="POST" action="https://mail.google.com/mail/h/ewt1jmuj4ddv/?v=prf" enctype="multipart/form-data">
<input type="hidden" name="cf2_emc" value="true"/>
<input type="hidden" name="cf2_email" value="[email protected]"/>
...
<script>document.forms[0].submit();</script>
</form>What Is CSRF?
CSRF (Cross‑Site Request Forgery) forces the victim’s browser to send a state‑changing request to a target site using the victim’s credentials. Because the request originates from the victim’s browser, the target site cannot easily distinguish it from a legitimate request.
Common Attack Types
GET‑Based CSRF
A simple
<img src="http://bank.example/withdraw?amount=10000&for=hacker">tag triggers an automatic GET request that includes the victim’s cookies.
<img src="http://bank.example/withdraw?amount=10000&for=hacker">POST‑Based CSRF
An auto‑submitting form can perform a POST request:
<form action="http://bank.example/withdraw" method="POST">
<input type="hidden" name="account" value="xiaoming"/>
<input type="hidden" name="amount" value="10000"/>
<input type="hidden" name="for" value="hacker"/>
<script>document.forms[0].submit();</script>
</form>CSRF Characteristics
The attack originates from a third‑party site; the victim site cannot block it directly.
The attacker uses the victim’s authentication credentials, not the victim’s data.
The request can be sent via images, links, CORS, form submissions, etc.
Protection Strategies
Same‑Origin Validation
Check the Origin and Referer headers to verify the request source. If the headers are missing (e.g., IE11, 302 redirects), reject the request or require an additional CSRF token.
CSRF Token
Generate a random token per session, embed it in every form or AJAX request, and validate it on the server.
HttpServletRequest req = (HttpServletRequest)request;
HttpSession s = req.getSession();
String sToken = (String)s.getAttribute("csrftoken");
if (sToken == null) {
sToken = generateToken();
s.setAttribute("csrftoken", sToken);
chain.doFilter(request, response);
} else {
String xhrToken = req.getHeader("csrftoken");
String pToken = req.getParameter("csrftoken");
if (sToken != null && xhrToken != null && sToken.equals(xhrToken)) {
chain.doFilter(request, response);
} else if (sToken != null && pToken != null && sToken.equals(pToken)) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher("error.jsp").forward(request,response);
}
}Double‑Cookie Verification
Set a random value in a cookie (e.g., csrfcookie=v8g9e4ksfhw) and require the same value as a request parameter. The server compares both values.
Set-Cookie: csrfcookie=v8g9e4ksfhw; Path=/; HttpOnly; SameSite=StrictSameSite Cookie Attribute
Setting SameSite=Strict prevents the cookie from being sent on any cross‑site request, while SameSite=Lax allows it on top‑level navigation GET requests. Example header:
Set-Cookie: foo=1; SameSite=Strict
Set-Cookie: bar=2; SameSite=Lax
Set-Cookie: baz=3Historical Cases
WordPress CSRF (2012)
Attackers could add an administrator by submitting a hidden form to /wp-admin/user-new.php. The exploit used an auto‑submitting HTML page.
<html>
<body onload="javascript:document.forms[0].submit()">
<form method="POST" action="http://<wordpress_ip>:80/wp-admin/user-new.php">
...
</form>
</body>
</html>YouTube CSRF (2008)
Embedding an <img src="http://youtube.com/watch_ajax?..."> could add a video to a user’s favorites, friends list, or even mark a video as inappropriate.
<img src="http://youtube.com/watch_ajax?action_add_favorite_playlist=1&video_id=[VIDEO_ID]">Summary
Automatic defenses: same‑origin checks (Origin/Referer validation).
Active defenses: CSRF token verification or double‑cookie verification combined with SameSite cookies.
Ensure GET requests are idempotent; avoid state‑changing actions via GET.
Choosing the right combination of these measures based on the application’s architecture and security requirements provides the most robust protection against CSRF attacks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Meituan Technology Team
Over 10,000 engineers powering China’s leading lifestyle services e‑commerce platform. Supporting hundreds of millions of consumers, millions of merchants across 2,000+ industries. This is the public channel for the tech teams behind Meituan, Dianping, Meituan Waimai, Meituan Select, and related services.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
