我正在使用 Helmet 并收到以下 console.log 消息之一:
:3000/:48 拒绝执行内联脚本,因为它违反了 遵循内容安全策略指令:“script-src ...”
我正在尝试找出哪些脚本被阻止。
我使用这些选项初始化了头盔:
const helmetOptions = {
crossOriginEmbedderPolicy: false,
contentSecurityPolicy: {
blockAllMixedContent: true,
directives: {
reportUri: '/report-violation',
defaultSrc: [self],
scriptSrc: [.....
在我的服务器上,我设置了这个来捕获发送到
reportUri
: 的消息
WebApp.connectHandlers.use('/report-violation', function (req, res, next) {
debugger;
const report = req.body;
console.log('cp #2. Helmet CSP Violation:', report);
next();
});
服务器功能正在受到影响,但
req.body
未定义 - 这是服务器控制台.log:
cp#2。头盔 CSP 违规:未定义
cp#2。头盔 CSP 违规:未定义
我错过了什么?
更新
我检查了是否需要对 req 主体进行 json 解析,但是 req 到达时已经被 json 解析为包含键和值的字段。
注意:服务器功能可能看起来有点时髦,但这就是您在 Meteor(我的构建工具)中访问 Express 的方式。 :)
这似乎有效:
WebApp.connectHandlers.use('/report-violation', (req, res, next) => {
// Check if the request method is POST
if (req.method === 'POST') {
let report = '';
req.on('data', chunk => {
report += chunk;
});
req.on('end', () => {
try {
// Attempt to parse the report as JSON
const parsedReport = JSON.parse(report);
try{
let violatedDirective = parsedReport["csp-report"]["violated-directive"]
let effectiveDirective = parsedReport["csp-report"]["effective-directive"]
let blockedUri = parsedReport["csp-report"]["blocked-uri"]
console.log('Helmet CSP Violation: ', blockedUri);
console.log('violated-directive: ', violatedDirective);
console.log('effective-directive: ', effectiveDirective);
console.log('-----');
}
catch (Exception){
console.log('No blockedUri was found.')
}
// Send a response indicating the method is allowed
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('POST method is allowed for this route.');
} catch (error) {
// Handle the case where the report is not valid JSON
console.error('Error parsing report as JSON:', error);
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Bad Request: Invalid JSON');
}
});
} else {
// If not POST, respond with a 405 status code and include the Allow header
res.writeHead(405, { 'Content-Type': 'text/plain', 'Allow': 'POST' });
res.end('Method Not Allowed');
}
// No need to call next() here since we're sending a response
});
注意:Meteor 的 WebApp.connectHanders 与express有一些差异。该代码需要修改才能与 Express 一起使用。