Implement Content Seguridad Policy (CSP)
CSP restricts qué resources (scripts, styles, images) un página puede cargar, preventing XSS y datos injection. Aprender policy directives y reporting.
- 1
CSP is an HTTP header (Content-Security-Policy) that whitelists resource sources. Directives: default-src (fallback), script-src (JavaScript), style-src (CSS), img-src, connect-src (fetch/XHR/WebSocket), font-src, frame-src, object-src. Use 'self' for same-origin, 'none' for nothing, nonces or hashes for inline scripts. CSP prevents XSS by blocking inline scripts and unauthorized sources.
- 2 Calculadora de hash →
Generar 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 Generador de HMAC →
Generar 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.
Preguntas frecuentes
- How do I migrate to CSP without breaking my site?
- Start with Content-Security-Policy-Report-Only (reports violations without enforcing). Use a report-uri or reporting-api to collect violations. Fix violations (move inline scripts to external files, add nonces/hashes). Once violations stop, switch to enforcing CSP. This gradual approach avoids breaking the site.
- CSP nonce vs hash?
- Nonce: random per-request value in header and script tag — allows any inline script with the nonce. Hash: SHA-256 of the script content in the header — allows only that exact script. Nonces are easier (one per page, not one per script) but require server-side generation. Hashes work for static pages but break when the script content changes (minification, deployment).