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

落爺英雄遲暮 提交于 2021-01-28 06:00:35

问题


This is my current script-src content security policy for my app:

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

trying to load the following external js code:

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

using unsafe-inline it works, but probably unsafe, so I want to remove it in my code, but then it doesn't allow the script to run. tried to add to script-src a value such as https://maps.googleapis.com/* but it still didn't work. how would one allow scripts from a specific domain?


回答1:


I had the same problem but was able to resolve it by using a hash with https://*.googleapis.com whitelisted.

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.

For example:

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

Note that for dynamic applications it's better to use a nonce.

Hope this helps!



来源:https://stackoverflow.com/questions/60758547/how-to-allow-content-security-policy-to-run-external-javascript-from-google-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!