出于某种原因,Chrome(或者至少是我的 Chrome)没有报告 CSP 违规行为。它正确地拒绝显示禁止的内容,但不报告违规行为。相比之下,Firefox 报告违规情况就好了。
考虑这个页面。您的浏览器不应在该页面中显示图像,因为该图像来自禁止的 URL。 Chrome 在这方面做得很好。但是,Chrome 不遵守 report-to 或 report-uri 指令(我都有)。同样,Firefox 遵守这些指令。
我知道浏览器可能会选择不报告多余的违规行为,但这里不是这种情况。 我试过使用不同urls但没有一个产生报告。
我使用的是 Chrome 版本 75.0.3770.90(正式版)(64 位)
任何帮助表示赞赏。
您可以监听'securitypolicyviolation'事件并手动报告
if(window.chrome /* and if not setting report-to using HTTP response headers */) {
document.addEventListener('securitypolicyviolation', (e)=> {
let reportToUrl='http://localhost:8080/api/csp-report'; // change it
fetch(reportToUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/csp-report'
},
body: JSON.stringify({
'csp-report':{
'blocked-uri': e.blockedURI,
'document-uri': e.documentURI,
'original-policy': e.originalPolicy,
'referrer': e.referrer,
'script-sample': e.sample,
'source-file': e.sourceFile,
'violated-directive': e.violatedDirective
}
}),
credentials: "omit",
cache: "no-cache",
referrerPolicy: "no-referrer"
});
});
}