I have been trying to solve some warnings from ZAP ( Medium ) but got no luck.I’m trying to run a React app ( currently testing enviroment) and despite setting CORS, Headers, and CSP on my backend ( express ) , it looks like for some URLs that i didn’t personally make (/static,/ws,/sitemap.xml I guess they are from React ) the rules wont apply
below is the backend code that works for most of my endpoints, but not for the above mentioned
app.use(helmet());
// Define the CORS middleware function
const allowCors = (req, res, next) => {
const allowedOrigin = 'http://localhost:3000'; // Specify the allowed origin
const origin = req.headers.origin;
console.log('Origin:', req.headers.origin); // Log the origin value
if (req.headers.origin === allowedOrigin || origin === 'http://localhost:5000/') {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Set Content-Security-Policy header with additional directives
const cspHeader = `
default-src 'self';
form-action 'self';
frame-ancestors 'self';
`.replace(/ns+/g, ' '); // Remove newlines and extra spaces from the header value
res.setHeader('Content-Security-Policy', cspHeader);
// Add anti-clickjacking header
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
console.log(res.headers)
next();
};
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(allowCors);
// Apply CORS middleware for a specific endpoint
app.use(limiter);
// Apply Helmet middleware for security headers
// Apply CSP configuration
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'","localhost:5000/",'"localhost:3000/'],
scriptSrc: ["'self'", "localhost:5000/", "https://js.stripe.com/"],
styleSrc: ["'self'", "https://fonts.googleapis.com"],
imgSrc: ["'self'", "http://localhost:5000/", "http://localhost:3000/", "data:"], // Add 'self' to imgSrc directive
fontSrc: ["'self'", "https://fonts.googleapis.com"], // Add 'self' to fontSrc directive
formAction: ["'self'"], // Define form-action directive to allow forms to submit to the same origin
frameAncestors: ["'self'"], // Define frame-ancestors directive to restrict embedding to the same origin
},
}));
aggelos spirou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.