Implement Content Security Policy (CSP)
CSP restricts 什么 resources (scripts, styles, images) page 能够加载, preventing XSS 和数据 injection. Learn 策略 directives 和报告.
- 1
CSP 是 HTTP 头 (Content-Security-Policy) 该 whitelists 资源源. Directives: default-src (fallback), 脚本-src (JavaScript), 风格-src (CSS), img-src, 连接-src (获取/XHR/WebSocket), 字体-src, 帧-src, object-src. Use 'self' 为相同-源, 'none' 为无, nonces 或 hashes 为 inline scripts. CSP prevents XSS 通过 blocking inline scripts 和未授权源.
- 2 哈希计算器 →
生成 a SHA-256 hash of inline script content for CSP hash-based allowlisting. The CSP directive: script-src 'sha256-<base64-hash>'. This allows only that specific inline script. Alternatively, use nonces: script-src 'nonce-<random>' and add nonce="<random>" to each script tag. Nonces are preferred (hashes break on minification).
- 3 HMAC 生成器 →
生成 a CSP nonce (number used once) for each page load. The nonce is a random base64 string included in the CSP header and each script tag. This allows inline scripts with the correct nonce while blocking unauthorized ones. Generate a fresh nonce per request — never reuse or hardcode it.
常见问题
- 如何 I migrate 到 CSP 无 breaking my site?
- 开始具有 Content-Security-Policy-报告-Only (reports violations 无 enforcing). Use 报告-uri 或报告-api 到 collect violations. Fix violations (move inline scripts 到外部 files, 添加 nonces/hashes). 一次 violations 停止, switch 到 enforcing CSP. 此 gradual 方法 avoids breaking site.
- CSP nonce vs hash?
- Nonce: random per-请求值 在头 和脚本 tag — allows 任何 inline 脚本具有 nonce. Hash: SHA-256 的脚本内容在 头 — allows 仅该 exact 脚本. Nonces 是 easier (one per page, 不 one per 脚本) 但 require 服务器-边 generation. Hashes 工作为 静态 pages 但 break 当脚本内容 changes (minification, 部署).