patternjavascriptCriticalpending
Content Security Policy (CSP) Configuration Guide
Viewed 0 times
CSPcontent security policyXSSnoncescript-srcsecurity headers
Problem
Web applications are vulnerable to XSS attacks. Content Security Policy headers can prevent script injection but are complex to configure correctly.
Solution
Start strict, then relax as needed:
Common directives:
Implementation:
# Strict CSP (best for new apps)
Content-Security-Policy:
default-src 'none';
script-src 'self';
style-src 'self';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
# With nonce-based inline scripts (recommended)
Content-Security-Policy:
script-src 'nonce-{random}' 'strict-dynamic';
# Report-only mode for testing
Content-Security-Policy-Report-Only:
default-src 'self';
report-uri /csp-report;Common directives:
default-src: Fallback for all resource typesscript-src: JavaScript sourcesstyle-src: CSS sourcesconnect-src: XHR, fetch, WebSocketframe-ancestors: Who can embed this page (replaces X-Frame-Options)
Implementation:
// Express middleware
const crypto = require('crypto');
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString('base64');
res.locals.nonce = nonce;
res.setHeader('Content-Security-Policy',
`script-src 'nonce-${nonce}' 'strict-dynamic'`);
next();
});Why
CSP is the strongest defense against XSS. Even if an attacker finds an injection point, CSP prevents unauthorized scripts from running.
Gotchas
- 'unsafe-inline' for scripts defeats most CSP benefits - use nonces instead
- strict-dynamic ignores allowlists - only nonce'd scripts and their children run
Context
Securing web applications against XSS
Revisions (0)
No revisions yet.