Content Security Policy and Modern Web Security

Content Security Policy (CSP) is a set of browser rules that tell a page where to load resources from. It helps reduce cross-site scripting (XSS) and other injection risks. With many sites moving to dynamic content, CSP is a key part of modern web security. It works best when combined with HTTPS and careful coding practices.

A CSP can be delivered by an HTTP header named Content-Security-Policy or, in simple cases, by a meta tag. The header is widely supported and applies to all subresources. A common starting point is a policy that limits all loads to the site itself: default-src ‘self’. From there, teams add sources for scripts, styles, images, and fonts.

Directives control groups of resources. Script-src governs JavaScript, style-src CSS, and img-src images. A practical starting policy might look like: default-src ‘self’; script-src ‘self’ https://cdn.example.com; style-src ‘self’ ‘unsafe-inline’. This keeps inline styles and external scripts under control while leaving room for trusted CDNs.

Nonces and hashes offer safer inline scripting. A nonce is a random value added to the policy and to individual inline scripts. A hash fingerprints a piece of inline code so it can run if it matches the hash in the policy. These methods let you keep necessary inline code while keeping a strict policy for everything else.

CSP can report violations to a URL or to a reporting group via the report-to mechanism. Start in report-only mode to gather data without breaking users, then switch to enforcement after testing. Reporting helps you see blocked assets, misconfigured sources, and broken third-party scripts.

Practical steps are straightforward. Audit existing assets and permissions, then publish a baseline policy in a header. Monitor browser console messages and CSP reports, and tighten sources gradually. Remove unsafe-inline as soon as you can and add nonces for any essential inline scripts. If you have subdomains, consider include-subdomains and frame-ancestors to prevent clickjacking.

In the modern web, CSP is powerful but not a lone shield. Use it with other headers like HSTS, X-Content-Type-Options, and X-Frame-Options. A thoughtful CSP reduces attack risk and helps engineering teams deploy safer, reliable sites for users worldwide.

Example policy lines describe how these rules look in practice, though actual values depend on your app: Content-Security-Policy: default-src ‘self’; script-src ‘self’ https://cdn.example.com; style-src ‘self’ ‘unsafe-inline’; img-src *; report-uri https://example.com/csp-report. Review and test carefully before enforcing across all pages.

Key Takeaways

  • CSP helps prevent XSS by controlling which sources can load scripts, styles, and other resources.
  • Start with a report-only mode, then tighten sources and add nonces or hashes for inline code.
  • CSP should be part of a broader security strategy, alongside other headers and secure development practices.