Lesson 39 of 55 · HTML
Security – Content Security Policy (CSP)
Duration: 9 min
Mitigating XSS with CSP
CSP is delivered via HTTP header or <meta> tag to restrict which resources can be loaded.
<meta http-equiv='Content-Security-Policy' content="default-src 'self'; img-src https://images.example.com; script-src 'self' 'sha256-abc123'; style-src 'self' https://fonts.googleapis.com;" />
Directive overview
default-src– Fallback for all resource types.script-src,style-src,img-src,font-src,connect-src,media-src,object-src– Fine‑grain control.- Hashes (
'sha256-…') or nonces ('nonce-…') allow specific inline scripts/styles. report-uri/report-to– URLs where violation reports (JSON) are sent.
Reporting mode
Content-Security-Policy-Report-Only– Lets you monitor violations without blocking resources; ideal for testing.
Common pitfalls
- Forgetting to whitelist required third‑party scripts (e.g., analytics, reCAPTCHA).
- Using
'unsafe-inline'defeats CSP’s purpose; avoid it unless you have a strong reason and use nonces instead. - Not including
upgrade-insecure-requestswhen a site serves mixed content.
Quick checklist for CSP
- CSP delivered via HTTP header (preferred) or
<meta>? ✅ default-srcset to'self'? ✅- Third‑party domains explicitly allowed? ✅
- Inline scripts/styles protected with nonces/hashes? ✅
Report‑Onlymode used during rollout? ✅
Tip: Start with a permissive policy in Report‑Only mode, gather violation reports, then tighten the policy step‑by‑step.