文件预览违反内容安全策略

Content Security Policy Violation on File Preview

这很奇怪,我四处检查并尝试了很多方法都无济于事。

我有一个简单的文件上传,它在上传之前显示图像。这在我的本地开发环境中工作正常,在登台服务器上也工作正常。

在生产服务器上,它不起作用。这是我的控制台中显示的内容:

refused to load the image 'blob:https://example.com/a7ced718-483b-4bc2-9db0-f012c8c6af5a' because it violates the following Content Security Policy directive: "img-src 'self' data:

但是,我没有定义 CSP,它在用于暂存以测试错误的精确副本服务器上运行良好。

另外,我尝试在文档头部的meta标签中添加CSP,也没有解决问题。这是我尝试实施的 CSP:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

任何人都可以阐明为什么这可能不起作用吗?

检查服务器发送的响应 header(使用浏览器开发工具或 curl 或其他)。

生产服务器必须发送 Content-Security-Policy 响应 header。

如果是这样,您的 meta 元素无效的原因是,浏览器使用 most-restrictive CSP 策略,无论在何处指定——以及 Content-Security-Policy header您发送的生产服务器比您使用 meta 元素指定的服务器更严格。

https://w3c.github.io/webappsec-csp/#multiple-policies and the details on the meta element at https://w3c.github.io/webappsec-csp/#meta-element 查看有关多项政策的详细信息 —

A policy specified via a meta element will be enforced along with any other policies active for the protected resource, regardless of where they’re specified. The general impact of enforcing multiple policies is described in §8.1 The effect of multiple policies.

8.1. The effect of multiple policies

The impact is that adding additional policies to the list of policies to enforce can only further restrict the capabilities of the protected resource.

所以您的生产服务器发送的 Content-Security-Policy header 似乎有 img-src 'self' data: 但为了让您的图像 URL 被允许并避免错误您看到了,您的生产服务器发送的 Content-Security-Policy header 至少还需要在其源列表中包含 blob:img-src 'self' data: blob:.