Overview
Content Security Policy is a browser feature that prevents content injection attacks. Define trusted sources for scripts, styles, and other resources.
Common Threats
- XSS (Cross-Site Scripting): Injected malicious scripts
- Clickjacking: Invisible elements over your page
- Data Exfiltration: Stealing user data
- Unsafe Plugins: Malicious browser plugins
- Man-in-the-Middle: Unencrypted traffic
Basic CSP Headers
Content-Security-Policy: default-src 'self'
Content-Security-Policy: script-src 'self' https://cdn.example.com
Content-Security-Policy: style-src 'self' 'unsafe-inline'
Content-Security-Policy: img-src * data: blob:
Comprehensive Policy
Content-Security-Policy:
default-src 'self';
script-src 'self' 'unsafe-inline' https://cdn.example.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src * data: blob:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self'
Express Implementation
import express from 'express'
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.com; style-src 'self' 'unsafe-inline'"
)
next()
})
Report Violations
Content-Security-Policy-Report-Only:
default-src 'self';
report-uri https://example.com/csp-report
// Report endpoint
app.post('/csp-report', express.json(), (req, res) => {
const report = req.body['csp-report']
console.log('CSP Violation:', {
blocked: report['blocked-uri'],
source: report['source-file'],
violation: report['violated-directive']
})
res.status(204).send()
})
Nonce for Inline Scripts
<!-- Generate nonce on server -->
<script nonce="random-value-here">
console.log('Safe inline script')
</script>
Content-Security-Policy: script-src 'self' 'nonce-random-value-here'
A well-configured CSP can prevent 95% of XSS attacks before they execute.