← 中文资源

简体中文版本

现代 Web 应用的安全边界

实用解读浏览器安全模型:同源策略、CSP、CORS、XSS 和 CSRF 防护如何组合成真正的边界。

阅读英文原文

引言

Web 安全边界不是单一机制,而是浏览器、协议和应用控制共同形成的多层约束。理解每层能防什么、不能防什么,比堆叠安全头更重要。

同源策略

同源策略限制脚本读取其他源的响应,但不阻止发送请求。它保护数据读取,不保护副作用,因此 CSRF 仍然存在。CORS 是服务端主动放宽读取限制的机制,不是访问控制。

CSP 与 XSS

CSP 通过限制脚本、样式和连接来源降低 XSS 影响。优先使用 nonce 或 hash,避免 unsafe-inline。XSS 的根本防御是输出编码和安全的 DOM API,CSP 是纵深防御而非替代品。

对 cookie 认证的变更请求,使用 SameSite、CSRF token 和 Origin 检查。HttpOnly 防止脚本读取 cookie,但不能阻止浏览器自动携带。敏感操作应重新认证。

组合边界

CORS 配置最小白名单,CSP 限制资源,SRI 校验第三方脚本,Trusted Types 防止 DOM 注入。每层都可能配置错误,因此要用测试和监控验证实际行为,而不是假设默认安全。

代码示例

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://cdn.example.com;
  style-src 'self' 'nonce-abc123';
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-src 'none';
  base-uri 'self';
  form-action 'self';
  object-src 'none';
const ALLOWED_ORIGINS = new Set(["https://app.example.com", "https://staging.example.com"]);

function corsHeaders(req: Request): Record<string, string> {
  const origin = req.headers.get("origin");
  if (!origin || !ALLOWED_ORIGINS.has(origin)) return {}; // do not send the header at all
  return {
    "Access-Control-Allow-Origin": origin, // specific, never *
    "Access-Control-Allow-Credentials": "true",
    "Vary": "Origin", // cache correctly per origin
  };
}
// Vulnerable: renders user input as HTML.
<div dangerouslySetInnerHTML={{ __html: user.bio }} />

// Safe: encodes by default.
<div>{user.bio}</div>

// Safe if you must render rich text: sanitize with an allowlist-based library.
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(user.bio) }} />
function csrfGuard(req: Request): void {
  if (req.method === "GET") return;
  const site = req.headers.get("sec-fetch-site");
  if (site && site !== "same-origin" && site !== "same-site") {
    throw new Forbidden("cross-site request blocked");
  }
  const token = req.headers.get("x-csrf-token");
  if (token !== req.session.csrfToken) throw new Forbidden("invalid csrf token");
}
<script src="https://cdn.example.com/lib.js"
        integrity="sha384-oqVuAfXRKap7fdgcCY5uykMNX+J1nXIV6pP"
        crossorigin="anonymous"></script>
if (window.trustedTypes) {
  const sanitizer = trustedTypes.createPolicy("sanitizer", {
    createHTML: (s: string) => DOMPurify.sanitize(s),
  });
  el.innerHTML = sanitizer.createHTML(userContent); // only policy output reaches the sink
}
res.cookie("__Host-session", token, {
  httpOnly: true, secure: true, sameSite: "strict", path: "/",
  // no domain -> host-only; the __Host- prefix enforces all of the above
});