๐ก๏ธ 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 originscript-src
: Allow scripts only from the same origin andapis.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
orhash
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.