Google 地图 API Key
梳理 Google Maps API Key 的历史申请流程与现代 Google Cloud Console 凭据配置迁移,并在离线 Chromium 中验证密钥格式与 HTTP 来源白名单守卫。
学完这一章,你能够
- 梳理 Google Maps API Key 的历史申请流程与现代 Google Cloud Console 凭据配置迁移,并在离线 Chromium 中验证密钥格式与 HTTP 来源白名单守卫。
申请 Google Maps API Key 的前期准备与历史控制台入口
在真实网站中调用 Google Maps JavaScript API 之前,必须先在 Google 平台注册项目并获取专属的 API Key。早年教程描述了免费申请的基本脉络,而在当前 Google Cloud 体系下,创建 API Key 还需为项目关联结算账号(享受每月免费额度)并启用 Maps JavaScript API。
历史步骤中需使用 Google 账号登录旧版控制台 `https://code.google.com/apis/console/` 进入项目概览界面(现代环境已全面迁移至 Google Cloud Console `https://console.cloud.google.com/`)。登录后的新建项目引导界面原参考图未在本地缓存,仅在私有核查记录中登记锚点。
启用地图服务、配置网站限制与妥善保存密钥
在控制台中点击 `Create Project` 新建项目后,需在服务列表中定位 `Google Maps API v3`(现代控制台名称为 `Maps JavaScript API`),将服务开关由关闭(`off`)切换为开启(`on`),并在协议确认页勾选同意条款(`I Agree...`)后点击 `Accept` 完成启用。
历史文档曾引导从左侧 `API Access` 进入 `Create an OAuth 2.0 client id...`,填写项目名称、图标并选择应用类型为网站应用(`Web application`)及站点域名后点击 `Create Client Id` 以查看凭据页中的 API Key。需要特别说明的是:在现代 Google Cloud Console 中,浏览器端加载 Maps JavaScript API 应直接在“API 和服务 → 凭据 → 创建凭据 → API 密钥”生成密钥(而非 OAuth 2.0 客户端 ID),并为其配置“网站(HTTP 引荐来源网址)”限制与“API 限制”。原结果截图未缓存,仅保留锚点记录。
生成密钥后务必妥善保管,且仅在已授权的站点 URL 下使用,避免在公开仓库硬编码无限制密钥导致额度被盗刷。本站离线 Chromium 实测验证了三项客户端守卫契约:构造加载地址时强制 `https:` 协议与 `/maps/api/js` 路径(`key` 长度 39 位、`callback=initMap`);HTTP Referrer 匹配允许 `https://app.example.com/*` 通过,而未授权来源 `https://untrusted.test/maps/demo` 返回 `RefererNotAllowedMapError`;当传入空值或占位符 `YOUR_API_KEY` 时前置校验拦截挂载并输出 `InvalidKeyMapError` 提示,换入合法格式密钥后正常就绪(`Map ready for app.example.com`)。
离线校验 Maps 加载 URL 构造、HTTP 来源白名单与占位密钥拦截
"""Offline Playwright Chromium lab for Google API Ch 02: google-maps-api-key."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Google Maps API Key 离线配置与校验实验</title>
<style>
#googleMap { width: 480px; height: 320px; border: 1px solid #cbd5e1; position: relative; }
.key-error { padding: 12px; color: #b91c1c; background: #fef2f2; font-family: sans-serif; }
.key-ok { padding: 12px; color: #166534; background: #f0fdf4; font-family: sans-serif; }
</style>
</head>
<body>
<div id="googleMap"></div>
<script>
window.MapsKeyContract = {
buildLoaderUrl(apiKey, callbackName) {
const url = new URL("https://maps.googleapis.com/maps/api/js");
url.searchParams.set("key", apiKey);
if (callbackName) url.searchParams.set("callback", callbackName);
return {
href: url.toString(),
protocol: url.protocol,
host: url.host,
pathname: url.pathname,
key: url.searchParams.get("key"),
callback: url.searchParams.get("callback"),
};
},
isValidKeyFormat(apiKey) {
if (!apiKey || apiKey === "YOUR_API_KEY") return false;
return /^AIza[0-9A-Za-z_-]{35}$/.test(apiKey);
},
checkReferrer(originUrl, allowedPatterns) {
const origin = new URL(originUrl);
for (const pattern of allowedPatterns) {
const regexStr = "^" + pattern
.replace(/[.+?^${}()|[\\]\\\\]/g, "\\\\$&")
.replace(/\\\\\\*/g, ".*")
.replace(/\\*/g, ".*") + "$";
if (new RegExp(regexStr).test(origin.toString())) {
return { allowed: true, error: null, matched: pattern };
}
}
return { allowed: false, error: "RefererNotAllowedMapError", matched: null };
},
mountWithKeyGuard(container, apiKey, currentUrl, allowedPatterns) {
if (!this.isValidKeyFormat(apiKey)) {
container.innerHTML = '<div class="key-error">InvalidKeyMapError: 请配置有效的 API Key</div>';
return { mounted: false, status: "InvalidKeyMapError" };
}
const refCheck = this.checkReferrer(currentUrl, allowedPatterns);
if (!refCheck.allowed) {
container.innerHTML = '<div class="key-error">' + refCheck.error + '</div>';
return { mounted: false, status: refCheck.error };
}
container.innerHTML = '<div class="key-ok">Map ready for ' + new URL(currentUrl).host + '</div>';
return { mounted: true, status: "OK" };
}
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page(viewport={"width": 800, "height": 600})
page.set_content(HTML_DOC, wait_until="load")
# Case 1: Loader URL construction (HTTPS + key + callback)
actual_url = page.evaluate("""() => {
const sampleKey = "AIza" + "0123456789abcdefghij0123456789abcde";
const info = window.MapsKeyContract.buildLoaderUrl(sampleKey, "initMap");
return {
protocol: info.protocol,
host: info.host,
pathname: info.pathname,
key_len: info.key.length,
callback: info.callback,
format_valid: window.MapsKeyContract.isValidKeyFormat(sampleKey)
};
}""")
expected_url = {
"protocol": "https:",
"host": "maps.googleapis.com",
"pathname": "/maps/api/js",
"key_len": 39,
"callback": "initMap",
"format_valid": True,
}
cases.append({
"name": "api_key_url_builder",
"passed": actual_url == expected_url,
"expected": expected_url,
"actual": actual_url,
})
# Case 2: HTTP referrer restriction verification
actual_ref = page.evaluate("""() => {
const allow = ["https://app.example.com/*"];
const ok = window.MapsKeyContract.checkReferrer("https://app.example.com/maps/demo", allow);
const bad = window.MapsKeyContract.checkReferrer("https://untrusted.test/maps/demo", allow);
return {
authorized_allowed: ok.allowed,
authorized_error: ok.error,
unauthorized_allowed: bad.allowed,
unauthorized_error: bad.error
};
}""")
expected_ref = {
"authorized_allowed": True,
"authorized_error": None,
"unauthorized_allowed": False,
"unauthorized_error": "RefererNotAllowedMapError",
}
cases.append({
"name": "http_referrer_restriction_check",
"passed": actual_ref == expected_ref,
"expected": expected_ref,
"actual": actual_ref,
})
# Case 3: Missing / placeholder key guard vs valid key DOM mount
actual_guard = page.evaluate("""() => {
const el = document.getElementById("googleMap");
const allow = ["https://app.example.com/*"];
const rPlaceholder = window.MapsKeyContract.mountWithKeyGuard(el, "YOUR_API_KEY", "https://app.example.com/", allow);
const errText = el.textContent.trim();
const sampleKey = "AIza" + "0123456789abcdefghij0123456789abcde";
const rValid = window.MapsKeyContract.mountWithKeyGuard(el, sampleKey, "https://app.example.com/store", allow);
const okText = el.textContent.trim();
return {
placeholder_status: rPlaceholder.status,
placeholder_mounted: rPlaceholder.mounted,
has_error_banner: errText.includes("InvalidKeyMapError"),
valid_status: rValid.status,
valid_mounted: rValid.mounted,
ok_banner: okText
};
}""")
expected_guard = {
"placeholder_status": "InvalidKeyMapError",
"placeholder_mounted": False,
"has_error_banner": True,
"valid_status": "OK",
"valid_mounted": True,
"ok_banner": "Map ready for app.example.com",
}
cases.append({
"name": "missing_or_placeholder_key_guard",
"passed": actual_guard == expected_guard,
"expected": expected_guard,
"actual": actual_guard,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 合法 39 位模拟密钥构造 https://maps.googleapis.com/maps/api/js?key=...&callback=initMap;授权来源 app.example.com 放行而 untrusted.test 报 RefererNotAllowedMapError;YOUR_API_KEY 触发 InvalidKeyMapError 提示栏。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:6ae19d902683c8c99838d26fe8e281d3ca2112f1f03c330a1e70ec03a3f3eecb
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:02c2af571b071528e667ac87abe325f3a0efe17328f13351d38dc4cd82a40821
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为何不能将未加限制的 Google Maps API Key 直接提交到公开前端代码中?应如何收紧权限?
展开参考解答
前端脚本中的 API Key 对访客可见,若不加限制极易被第三方域名盗用并产生异常计费。应在 Google Cloud Console 中同时配置 HTTP Referrer 网站白名单与仅限 Maps JavaScript API 的接口限制。