JAVASCRIPT
Implement a Content Security Policy (CSP) Manually
Manually configure a robust Content Security Policy (CSP) header in your Express.js application to mitigate various types of XSS and data injection attacks.
// This example assumes an Express.js application.
const express = require('express');
const app = express();
const port = 3000;
// Middleware to set Content-Security-Policy header
app.use((req, res, next) => {
const cspDirectives = [
"default-src 'self'", // Only allow resources from the same origin by default
"script-src 'self' 'unsafe-inline' https://cdn.example.com", // Allow scripts from self and a specific CDN
"style-src 'self' 'unsafe-inline'", // Allow styles from self and inline styles (careful with 'unsafe-inline')
"img-src 'self' data: https://images.example.com", // Allow images from self, data URIs, and a specific image host
"font-src 'self' https://fonts.gstatic.com", // Allow fonts from self and Google Fonts
"connect-src 'self' api.example.com", // Allow fetch/XHR from self and a specific API endpoint
"frame-ancestors 'none'", // Prevent framing the site (clickjacking protection)
"object-src 'none'", // Block plugins like Flash
"base-uri 'self'" // Restrict what URLs can be used in <base> tags
// 'report-uri /csp-report-endpoint' // Uncomment to report violations to a specific URL
// 'upgrade-insecure-requests' // Uncomment to ensure all requests are HTTPS
];
res.setHeader('Content-Security-Policy', cspDirectives.join('; '));
next();
});
app.get('/', (req, res) => {
res.send('<h1>Hello, CSP!</h1><script>console.log(\'This script is allowed.\');</script>');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to manually implement a Content Security Policy (CSP) by setting the `Content-Security-Policy` HTTP header. CSP is a powerful security mechanism that helps mitigate XSS and data injection attacks by restricting the sources from which content can be loaded (scripts, styles, images, etc.). The directives specify allowed origins and types of resources, making it harder for attackers to inject and execute malicious code. `frame-ancestors 'none'` is particularly important for preventing clickjacking.