内容安全政策指南

本文档提供了有关如何为 Maps JavaScript API 配置网站内容安全政策 (CSP) 的建议。由于最终用户使用的浏览器类型和版本多种多样,因此建议开发者参考此示例进行微调,直至不再出现 CSP 违规行为。

详细了解内容安全政策

严格 CSP

我们建议您使用严格 CSP(而不是许可名单 CSP),以降低遭到安全攻击的可能性。Maps JavaScript API 支持使用基于 Nonce 的严格 CSP。网站必须使用 Nonce 值填充 scriptstyle 元素。在内部,Maps JavaScript API 会查找第一个这类元素,然后将其 Nonce 值分别应用于该 API 脚本插入的样式或脚本元素。

示例

以下示例展示了一个示例 CSP,以及嵌入了该 CSP 的 HTML 网页:

内容安全政策示例

script-src 'nonce-{script value}' 'strict-dynamic' https: 'unsafe-eval' blob:;
img-src 'self' https://*.googleapis.com https://*.gstatic.com *.google.com *.googleusercontent.com data:;
frame-src *.google.com;
connect-src 'self' https://*.googleapis.com *.google.com https://*.gstatic.com data: blob:;
font-src https://fonts.gstatic.com;
style-src 'nonce-{style value}' https://fonts.googleapis.com;
worker-src blob:;

HTML 网页示例

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css" nonce="{style value}">
    <style nonce="{style value}">...</style>
    ...
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async nonce="{script value}"></script>
    <script nonce="{script value}"> function initMap() { ... } </script>
  </body>
</html>

许可名单 CSP

如果您已设置许可名单 CSP,请参阅 Google 地图域名列表。我们建议您参阅本文档和 Maps JavaScript API 版本说明,及时了解最新动态,并根据需要将任何新的服务网域列入许可名单。

如果网站从旧版 Google API 网域(例如 maps.google.com)或区域专用网域(例如 maps.google.fr)加载 Maps JavaScript API,还必须在其 CSP script-src 设置中包含这些域名,如以下示例所示:

script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.googleapis.com https://*.gstatic.com *.google.com https://*.ggpht.com *.googleusercontent.com blob:;
img-src 'self' https://*.googleapis.com https://*.gstatic.com *.google.com  *.googleusercontent.com data:;
frame-src *.google.com;
connect-src 'self' https://*.googleapis.com *.google.com https://*.gstatic.com  data: blob:;
font-src https://fonts.gstatic.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
worker-src blob:;