保护 Google 映射 JavaScript API 密钥

Protecting Google Maps JavaScript API key

我是 javascript 的新手。我正在使用 Google 地图 JavaScript API 在我的站点中包含自动完成功能。该代码需要 API 键才能执行。

<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>

我想保护这个 API 密钥,因为它是公开的,任何人都可以在浏览器上使用 view page source 查看我的 javascript 代码。

如何保护这个 API 密钥,使其不被公开??

Google 地图有多种 API 键。

浏览器/Javascript 键用于获取 JS/前端库,可以使用。

只需确保您使用的是浏览器密钥,可在此处找到:https://developers.google.com/maps/documentation/javascript/get-api-key

您可以进一步添加安全限制以防止密钥被用于其他地方。您也可以按域、IP 地址、android、ios 应用程序进行限制。

注意,服务器端密钥应该是私有的。

由于您要在前端应用程序 Javascript 中使用此密钥,因此没有万无一失的方法来保护它。

您可以做的最好的事情是使用基于 Referer header 的应用程序限制来限制您的 api 密钥,并且 API 限制仅限于地图 API。

https://developers.google.com/maps/documentation/javascript/get-api-key#restrict_key

https://cloud.google.com/docs/authentication/api-keys#adding_http_restrictions

这使得一些其他应用程序很难冒充您的应用程序,因为模仿 Referer header 并非易事,特别是从前端应用程序。

https://security.stackexchange.com/questions/152066/what-is-the-point-of-restricting-a-google-api-key-by-http-referer