无法使用 Google 地图 API 实施严格的内容安全策略

问题描述

我在chrome的开发者工具的控制台中多次遇到以下错误,用于maps.googleapis.com的common.js文件-

common.js:15 
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://fonts.googleapis.com https://s3.amazonaws.com https://maxcdn.bootstrapcdn.com". Either the 'unsafe-inline' keyword,a hash ('sha256-mmA4m52ZWPKWAzDvKQbF7Qhx9VHCZ2pcEdC0f9Xn/Po='),or a nonce ('nonce-...') is required to enable inline execution.

我需要使用严格的 CSP 政策,所以不能使用 unsafe-inline 或 unsafe-eval 来放松政策。 为了支持严格的 CSP 策略,不允许使用内联样式和脚本。由于我收到上述错误,似乎在 google map api 的 common.js 中使用了内联样式。

有什么建议吗?

enter image description here

解决方法

目前谷歌地图要求您在 unsafe-inline 的 CSP 中有 style-src。对于script-src,它仍然有效。~~

上述CSPlite.com授权测试已调整;在撰写此答案时the test says

在 2021 年 4 月下旬,Google 地图脚本停止将 'nonce-value' 从父脚本传递到子样式块 <style>...</style>

我找到的临时解决方案是将 Google 地图中的所有样式添加到我们的第三方 CSS 代码中。这样,您仍然会在控制台中遇到错误,但 style-src 阻止来自 Google 地图的内联样式导致的视觉错误将消失。我们使用的方法是将谷歌地图添加的所有内联样式复制过来。

如果您找到了这个答案,并且还希望 Google Maps 再次支持将 nonce 值分发到其内联样式块,please leave a comment here

编辑 22-06-2021:

GMap 还没有正式支持 nonce。最近发生了变化,改进了 Maps JS 处理脚本和样式的单独随机数的能力。现在,如果站点在 <style><link rel="stylesheet"> 上没有 nonce,这将导致没有 nonce 应用于 Maps JS 样式表。

作为一种变通方法,您的网站可以包含一个空的 <style> 并提供随机数,GMaps JS 会选择它。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...