【发布时间】:2020-06-23 06:22:42
【问题描述】:
我在文档中读到,为了使用 Google Direction API Web 服务,I needed to use IP restrictions。所以为了实现这个功能,我创建了一个代理服务器,为我提供我想要的方向。链接如下:
https://myapp-44th7.uc.r.appspot.com/?origin=22.174181,33.6436763&destination=22.189821,33.640532
当我使用 unrestricted API 密钥并在浏览器中访问此 URL 时,它工作正常,我得到了所需的 JSON 文件。当我想限制它时,问题就来了。我无法添加单个 IP 地址作为限制,因为我的 Android 应用程序被具有许多不同 IP 地址的用户使用。我很难理解如何限制这一点。请帮助解决这个问题。我应该添加什么IP?
编辑:
package main
import (
"fmt"
"net/http"
"io/ioutil"
"context"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
const directionAPIKey = "..............uFvjU"
const directionURL = "https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&mode=%s&key=%s"
func main() {
http.HandleFunc("/", handler)
appengine.Main()
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
direction, err := fetchDirection(ctx, r.FormValue("origin"), r.FormValue("destination"), r.FormValue("mode"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json; charset=utf-8")
w.Write(direction)
}
func fetchDirection(ctx context.Context, origin string, destination string, mode string) ([]byte, error) {
client := urlfetch.Client(ctx)
resp, err := client.Get(fmt.Sprintf(directionURL, origin, destination, mode, directionAPIKey))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
directionAPIKey 是我在 URL 中用来访问的密钥:
https://myapp-44th7.uc.r.appspot.com/?origin=22.174181,33.6436763&destination=22.189821,33.64053&key=..............uFvjU
And the one for which I added the restriction in the GCP。 172.217.23.52 是我 ping myapp-44th7.uc.r.appspot.com 时的 IP。
【问题讨论】:
-
您的服务器的 IP 地址(不是调用它的各个设备的 IP 地址)。要求您的服务器具有固定的 IP 地址。您只在您控制的服务器上的代码上使用它来保护您的密钥(并且不公开发布)
-
@geocodezip 如果我 ping
myapp-44th7.uc.r.appspot.com,是的,我得到一个固定的 IP 地址。如果我将该 IP 添加为 GCP 中的限制,我会在尝试访问它时收到以下错误消息。This IP, site or mobile application is not authorized to use this API key. Request received from IP address 35.243.XX.XX, with empty referer。我不确定我是否理解您所说的“您只在服务器上的代码上使用它来保护您的密钥”是什么意思? -
将密钥附加到从您的服务器(需要具有固定 IP 地址)发送到 Google 服务器的请求中。
-
@geocodezip 所以你基本上说在我的问题中应该将受限密钥附加到 URL 中?如果在 URL 中首先添加或最后添加密钥,顺序是否重要?
-
查看有关如何创建 Web 服务请求的文档。
标签: google-maps google-maps-api-3 google-cloud-platform google-cloud-console google-directions-api