5

Is it possible to restrict the Time Zone API key to Android Apps?

Google Maps Android API and Google Places API keys can be restricted to certain Androids Apps by defining the package name and SHA-1 hash.

This works without problem for the Maps and Places API, but using the exact same settings for the Time Zone API constantly returns "REQUEST_DENIED". Setting the application restrictions back to "None" results in a successful query, but I don't want to leave my API key unprotected.

The way I'm calling the API is as follows:

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();
        }
}

The received response is:

{
"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"
}

If I set the Application restriction to None, everything works:

{
"dstOffset" : 3600,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "British Summer Time"
}
Folli
  • 173
  • 1
  • 8

1 Answers1

2

I've found out that this is essentially the same issue as described here: Android Google Maps Direction Api - Api key restriction not working

In short, Google Maps Android API is a webservice and the only API key restrictions that work are IP restrictions (App restrictions work for Android APIs only).

So you're left with only one solution: Implement an intermediate server that receives queries from your app, queries the Google API, and responds to your app by passing the Google API response. In this way it's possible to restrict the API key to your intermediate servers IP.

However, how you restrict the access to your intermediate server against third parties is a question on its own.

Folli
  • 173
  • 1
  • 8