使用Google Direction API时如何使用IP限制?

我在文档中读到为了使用Google Direction API网络服务I needed to use IP restrictions。因此,要实现此功能,我创建了一个代理服务器,可以为我提供所需的指导。链接看起来像这样:

https://myapp-44th7.uc.r.appspot.com/?origin=22.174181,33.6436763&destination=22.189821,33.640532

当我使用不受限制的API密钥并在浏览器中访问此URL时,它工作正常,我得到了所需的JSON文件。当我想限制它时,问题就来了。我无法添加一个IP地址作为限制,因为具有许多不同IP地址的用户使用我的Android应用。我很难理解如何限制这一点。请帮助解决此问题。我应该添加什么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.64053&key=..............uFvjU

And the one for which I added the restriction in the GCP172.217.23.52是当我ping myapp-44th7.uc.r.appspot.com时出现的IP。

iCMS 回答:使用Google Direction API时如何使用IP限制?

要使用IP限制来限制API密钥,您需要添加服务器的面向公众的IP地址作为对API密钥的限制。更多信息here

将IP限制应用于API密钥后,仅允许来自特定服务器(在您的情况下为代理服务器)的请求使用您的受限制的API密钥 。这意味着除了来自您设置为限制的IP地址之外,所有来自不同IP地址的请求都将被阻止。这就是为什么尝试使用受限API密钥直接从浏览器发送请求时会出错的原因,因为浏览器的IP地址与代理服务器的IP地址不同。

要确保您的受限API密钥有效,您可以验证是否可以使用受限API密钥通过代理服务器成功发送Directions API request

希望这会有所帮助!

本文链接:https://www.f2er.com/2076754.html

大家都在问