如何允许内容安全策略从 google api 运行 外部 javascript?

How to allow content security policy to run external javascript from google api?

这是我当前应用程序的脚本源内容安全策略:

script-src 'self' 'unsafe-inline' https://maps.googleapis.com https://maps.gstatic.com;

正在尝试加载以下外部 js 代码:

https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&libraries=places&language=he

使用 unsafe-inline 它可以工作,但可能不安全,所以我想在我的代码中删除它,但它不允许脚本 运行。 试图向 script-src 添加一个值,例如 https://maps.googleapis.com/* 但它仍然不起作用。 如何允许来自特定域的脚本?

我遇到了同样的问题,但可以通过使用 hash 并将 https://*.googleapis.com 列入白名单来解决。

The script-src directive lets developers whitelist a particular inline script by specifying its hash as an allowed source of script.

Usage is straightforward. The server computes the hash of a particular script block’s contents, and includes the base64 encoding of that value in the Content-Security-Policy header.

例如:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-...4aQo=' https://*.googleapis.com">

请注意,对于动态应用程序,最好使用 nonce

希望对您有所帮助!