5

是否可以将时区 API 密钥限制为 Android 应用程序?

通过定义包名称和 SHA-1 哈希,可以将 Google Maps Android API 和 Google Places API 密钥限制为某些 Android 应用程序。

这对 Maps and Places API 来说没有问题,但对 Time Zone API 使用完全相同的设置会不断返回“ REQUEST_DENIED”。将应用程序限制设置回“无”会导致查询成功,但我不想让我的 API 密钥不受保护。

我调用API的方式如下:

double lat = 51.1789;
double lon = -1.8262;
long time = 1523092938; 
String Api_key = "#API_KEY#";

String query = "https://maps.googleapis.com/maps/api/timezone/json?location="+String.format(Locale.ROOT, "%.4f",lat)+","+String.format(Locale.ROOT, "%.4f",lon)+"&timestamp="+time+"&key="+ Api_key;

protected JSONObject doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(query);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.connect();

            System.out.println(query);


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);
            }
            return new JSONObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
}

收到的响应是:

{
"errorMessage" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address XX.XX.XX.XX, with empty referer",
"status" : "REQUEST_DENIED"
}

如果我将应用程序限制设置为无,一切正常:

{
"dstOffset" : 3600,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "British Summer Time"
}
4

1 回答 1

2

我发现这与此处描述的问题基本相同:Android Google Maps Direction Api - Api key Restriction not working

简而言之,Google Maps Android API 是一种网络服务,唯一有效的 API 密钥限制是 IP 限制(应用程序限制仅适用于 Android API)。

因此,您只剩下一个解决方案:实现一个中间服务器,它接收来自您的应用程序的查询、查询 Google API,并通过传递 Google API 响应来响应您的应用程序。通过这种方式,可以将 API 密钥限制为您的中间服务器 IP。

但是,如何限制第三方对中间服务器的访问本身就是一个问题。

于 2018-04-10T05:27:40.073 回答