我应该采取什么步骤来保护我的谷歌地图 API 密钥?

我已经获得了我的域名的谷歌地图 API 密钥。

获取密钥时提供的示例显示了嵌入在请求参数中的密钥,例如:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true_or_false&amp;key=my-key" type="text/javascript"></script>

我理解请求中的引用字段必须与我的域相匹配,在脚本标记等中显示我的密钥是否安全?还有其他我应该采取的措施吗?

56597 次浏览

Considering that key has to be included in the <script> tags of your HTML pages, to load the JS files/data from google's servers, there is nothing you can do :

  • you must put it in your HTML files
  • every one can take a look at those.

Still, it doesn't really matter : if anyone tries to use this key on another domain than yours, they will get a Javascript alert -- which is not nice for ther users.

So :

  • There is nothing you can do ; this is the way it works
  • And there is not much you should worry about, I'd say.

There is setting on Google API console that can protect your API bandwith usage from being used by another domain/user. You can restrict and protect that by using referrer on the API console. API Key will reject requests without referrers that match your restrictions.

Here is screenshot from Google for API Key that can only be used by Google frowm its two domains. enter image description here

Though this question is a few years old it's a very good one. As I understand it exposing API keys, even if they are domain matched, could still lead to abuse. There's a post on Security Stack Exchange here that covers this in more detail.

The steps that you can take to avoid potential abuse have been published by Google here:

Best Practice Guide for securely using APIs: https://support.google.com/cloud/answer/6310037?hl=en

Though I would recommend taking all of it on board, there is an approach that would deal with the specific example that was posted by Brabster and that's to store the key in an environment variable. This way all you need to do is to substitute the key for a server-side variable that is stored within your project. However, be sure not to commit the file that stores the key to a public repository.

You should use back end/server side to protect and handle key. In my case I used Django f/w server side which can serve a ajax call to get the key from server script/db then pass it onto google api.