SmartCodingTips

๐Ÿ›ก๏ธ Content Security Policy (CSP) Explained

A Content Security Policy (CSP) is a browser security feature that helps prevent cross-site scripting (XSS), data injection, and code execution attacks by restricting the sources from which content can be loaded.

๐Ÿ” What CSP Does

CSP allows you to define which sources the browser should trust for loading resources like scripts, styles, images, fonts, and more.

๐Ÿ“ฆ Example CSP Header

Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com; object-src 'none';
  • default-src 'self': Only allow resources from the same origin
  • script-src: Allow scripts only from the same origin and apis.example.com
  • object-src 'none': Block Flash, plugins, etc.

๐Ÿšซ Preventing Inline Scripts

By default, CSP blocks inline JavaScript unless you allow it explicitly using 'unsafe-inline' (which is not recommended).

// โŒ This will be blocked if CSP disallows inline scripts
<script>alert("XSS!")</script>

๐Ÿ” Safer Alternatives

  • Use external scripts with proper script-src rules
  • Use nonce or hash based validation for inline scripts

๐Ÿ”‘ Example with Nonce

// Header:
Content-Security-Policy: script-src 'nonce-abc123'

// HTML:
<script nonce="abc123">console.log("Secure inline script")</script>

โš™๏ธ Setting CSP in Different Languages

PHP:

header("Content-Security-Policy: default-src 'self'; script-src 'self';");

Express (Node.js):

res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'");

๐Ÿงช Testing Your CSP

  • Use browser DevTools โ†’ Console for CSP violations
  • Use Google CSP Evaluator
  • Check headers using curl -I or browser DevTools
๐Ÿ’ก Tip: Start with Content-Security-Policy-Report-Only to monitor without breaking your site.