Content Security Policy (CSP) headers are a crucial security feature for modern web applications. They help prevent cross-site scripting (XSS) attacks by controlling which resources can be loaded by the browser. Implementing CSP headers can vary depending on the web framework you use. This guide provides practical steps for popular frameworks.
Understanding CSP Headers
CSP headers are sent by the server to instruct browsers on what content is allowed to load. They can specify trusted sources for scripts, styles, images, and other resources. Proper configuration enhances your website’s security without compromising functionality.
Implementing CSP in Different Frameworks
Express.js (Node.js)
In Express.js, use the helmet middleware to set CSP headers easily. Install it via npm:
npm install helmet
Then, configure helmet in your app:
app.js:
const express = require('express');
const helmet = require('helmet');
const app = express();
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'cdn.example.com'],
styleSrc: ["'self'", 'fonts.googleapis.com'],
imgSrc: ["'self'", 'images.example.com'],
},
})
);
app.get('/', (req, res) => {
res.send('Hello, CSP with Express!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Apache Web Server
For Apache, add the following directives to your .htaccess file or your site's configuration:
Header set Content-Security-Policy "default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' fonts.googleapis.com; img-src 'self' images.example.com;"
NGINX
In your NGINX configuration, include the following line inside the server block:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' fonts.googleapis.com; img-src 'self' images.example.com;";
Testing and Validating Your CSP
After implementing CSP headers, test your website using tools like Google's CSP Evaluator or browser developer tools. Check for blocked resources and adjust your policy accordingly to ensure full functionality.
Best Practices
- Start with a report-only policy to monitor potential issues.
- Gradually tighten the policy based on your site's needs.
- Regularly review and update your CSP as your site evolves.
- Combine CSP with other security measures like HTTPS and secure cookies.
Implementing CSP headers is a vital step toward securing your web applications. By tailoring policies for your specific framework, you can protect your site and your users from common vulnerabilities.