內容安全政策指南

本文件提供 Maps JavaScript API 網站內容安全政策 (CSP) 的設定建議。使用者會使用各式各樣的瀏覽器類型和版本,因此建議開發人員將本範例做為參考並進行微調,直到不再違反 CSP 為止。

進一步瞭解內容安全政策

嚴格 CSP

我們建議您使用嚴格 CSP 而非許可清單 CSP,以降低遭受安全性攻擊的可能性。Maps JavaScript API 支援使用以 Nonce 為基礎的嚴格 CSP。網站必須在 scriptstyle 元素中填入 Nonce 值。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:;