API Google 的密钥限制 API 从 URL 在 App Engine 中获取调用

API Key Restriction for Google API Called from URL Fetch within App Engine

我有一个 Google API 的 API 密钥,我想在对它的所有请求中使用它。其中一些请求将来自 Google App Engine (Python 2.7) 应用程序。本来打算用UrlFetch库来完成POST请求,基本如下:

headers = {'Content-Type': 'application/json'}
payload = {'longUrl': request.long_url}
result = urlfetch.fetch([API_REQUEST_URL],
                method=urlfetch.POST,
                payload=json.dumps(payload),
                headers=headers)

json_result = json.loads(result.content)

我已将我的 API 密钥设置为 *.[my-app].appspot.com/* 的引荐来源限制,希望这样可以保护我的 API 密钥免遭未经授权的使用并无需更新 IP基于密钥的限制(因为 App Engine IP 一直在变化)。

虽然这种方法让我失败了,因为 urlfetch 似乎没有为自己指定引荐来源网址的值。我想我可以添加自己的推荐人,但其他人也可以。该方法不是很安全。

最佳做法是什么?鉴于我在 App Engine 中使用 urlfetch,我应该如何限制密钥?如果我使用 HTTP Referrer 限制,我应该使用哪个地址?

非常感谢。

你喜欢这条错误信息吗?

Requests from referer <empty> are blocked.

urlfetch 似乎不会自动附加 Refer,因此您应该在请求 header.

中设置 Refer
headers = {'Content-Type': 'application/json','Referer': '*.[my-app].appspot.com/*'}

如您所见,引荐来源网址 header 可以伪造,因此在您的 API 密钥上设置引荐来源网址限制一开始是毫无用处的。

但您可以添加基于 X-Appengine-Inbound-Appid header 的检查,该检查已由 GAE 基础设施清理并精确识别应用程序。来自 Issuing a request to another App Engine app:

When issuing a request to another App Engine app, your App Engine app must assert its identity by adding the header X-Appengine-Inbound-Appid to the request. If you instruct the URL Fetch service to not follow redirects, App Engine will add this header to requests automatically.

To instruct the URL Fetch service to not follow redirects, set the fetch follow_redirects parameter to False.

Note: If you are making requests to another App Engine application, use its appspot.com domain name rather than a custom domain for your app.