Web Security 基础
学习 web security 基本 — XSS, CSRF, HTTPS, and 内容 Security Policy.
你将学到
- OWASP 顶部 10 and 大多数常见 web vulnerabilities
- XSS (Cross-Site Scripting): 如何它 工作 and 如何 prevent 它
- CSRF (Cross-Site 请求 Forgery) and SameSite Cookie defense
- 如何 HTTPS, CSP, and security 请求头 protect 你的 application
概念讲解
Web Security Basics
Web security is about protecting your users and your application from attackers. The web is a hostile environment — any public site is probed by automated bots within minutes of going live. You do not need to be a security expert to build safe web apps, but you must understand the most common attacks and their defenses. The OWASP Top 10 lists the ten most critical web vulnerabilities; we cover the ones every developer must know.
XSS (Cross-Site Scripting)
XSS happens when an attacker injects malicious JavaScript into your page, and the browser executes it. This can steal cookies, redirect users, or deface the page. The primary defense is never insert untrusted data as HTML. Use textContent instead of innerHTML. If you must render HTML from user input, sanitize it with a library like DOMPurify first. XSS is the most common web vulnerability — and the most preventable.
CSRF (Cross-Site Request Forgery)
CSRF tricks the user's browser into making a request to your site while the user is logged in, performing an action they did not intend (like transferring money). The browser automatically sends the user's session cookie, so the request looks legitimate. Defenses: use SameSite=Strict cookies (the modern, simplest defense), require a CSRF token for state-changing requests, or check the Origin or Referer header. SameSite cookies have made CSRF much less common, but it is still a risk on older browsers.
HTTPS and TLS
HTTPS encrypts traffic between the browser and server. Without it, anyone on the network can read passwords, cookies, and personal data. HTTPS is now the default — browsers flag HTTP sites as "Not Secure," and many features (service workers, geolocation) require it. Use Let's Encrypt for free certificates, redirect all HTTP to HTTPS, and set the Strict-Transport-Security header to enforce HTTPS in the future. There is no reason to use plain HTTP in production.
Content Security Policy (CSP)
CSP is an HTTP header that restricts what the browser is allowed to load and execute — scripts, styles, images, connections. A strong CSP is the most effective XSS mitigation because even if an attacker injects a <script> tag, the browser will not execute it if the CSP does not allow inline scripts. A basic CSP:
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'
This says: only load resources from the same origin. No inline scripts, no third-party CDNs (unless you add them to the allowlist). CSP is powerful but requires careful configuration — start with report-only mode to find violations before enforcing.
Security Headers
Beyond CSP, several headers harden your app: X-内容-类型-Options: nosniff (prevents MIME sniffing), X-Frame-Options: DENY (prevents clickjacking), Referrer-Policy: strict-原点-当-cross-原点 (limits referrer leakage). Tools like securityheaders.com audit your headers and tell you what is missing.
示例代码
// Defense 1: Prevent XSS — never use innerHTML with user data
function renderComment(userInput) {
const div = document.createElement("div");
// SAFE: textContent treats input as plain text
div.textContent = userInput;
// DANGEROUS: div.innerHTML = userInput; // NEVER do this!
return div;
}
// Defense 2: Sanitize if you must render HTML
// import DOMPurify from 'dompurify';
function renderRichText(userInput) {
const div = document.createElement("div");
div.innerHTML = DOMPurify.sanitize(userInput);
return div;
}
// Defense 3: CSRF token for state-changing requests
async function transferMoney(amount, toAccount) {
const csrfToken = document.querySelector("meta[name=csrf-token]").content;
const response = await fetch("/api/transfer", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken // server verifies this
},
credentials: "include",
body: JSON.stringify({ amount, toAccount })
});
return response.json();
}
renderComment uses textContent 到 safely display 用户输入 as 文本. renderRichText sanitizes 使用 DOMPurify 之前设置 innerHTML — 必要 for rich 文本但 从不 raw. transferMoney 包含 CSRF 令牌请求头那个服务器验证, preventing forged 请求. Together 这些 defend 针对 XSS and CSRF.
动手试一试
- HTML Entity Encoder
Encoding HTML entities 是键 XSS defense — encode 用户内容之前 display.
- Hash Generator
CSRF 令牌是 经常 random hashes — generate one 到 see 如何它们工作.
- JWT Decoder
理解 JWT 结构 — secure alternative 到存储认证状态 in Cookie.
常见错误
错误写法
Using innerHTML 使用用户输入, 创建 XSS vulnerability.
正确做法
Use textContent for 所有用户-provided 文本 — 它渲染 as plain 文本, 不 HTML. 如果你 需要 rich 文本, sanitize 使用 DOMPurify or 相似库 之前设置 innerHTML. 从不 concatenate 用户输入到 HTML 字符串.
错误写法
Serving site over HTTP in production or 不 redirecting HTTP 到 HTTPS.
正确做法
Use HTTPS everywhere in production. 获取 free certificates 从 Let's Encrypt, redirect 所有 HTTP traffic 到 HTTPS, and 设置 Strict-Transport-Security 请求头所以浏览器总是 uses HTTPS for 你的领域.
相关资源
相关指南
- JWT Security 指南
Secure 令牌 handling as 部分的 defense-in-深度 security 策略.
练习 Web Security 基础
7 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。