Adding restrictions to API keys

API keys identify your application or website to Google Cloud. API key restrictions ensure that only your apps and websites can use your keys. For security reasons, we recommend that you add restrictions that specify:

If a client uses a restricted API key to issue a request that doesn't satisfy the API key restrictions, then the request fails. For example, if an API key requires HTTP requests to be issued from a specific domain but an HTTP request is received from a different domain, the request will be rejected with an error.

You can add restrictions when you create an API key with the CreateKey method, or you can add the restrictions after the key is created using the UpdateKey method. This page describes the restrictions that you can add to an API key, and it shows you how to add those restrictions.

Adding client restrictions

Client restrictions specify which websites, IP addresses, or apps can use an API key. You add client restrictions based on the type of client that calls your API. You can specify one of the following types of client restrictions:

  • browserKeyRestrictions: The HTTP referrers (websites) that are allowed to use the key.
  • serverKeyRestrictions: The IP addresses of callers that are allowed to use the key.
  • androidKeyRestrictions: The Android apps that are allowed to use the key.
  • iosKeyRestrictions: The iOS apps that are allowed to use the key.

Adding browser restrictions

The following example shows how to call the UpdateKey method to restrict the HTTP referrer to www.example.com:

curl -X PATCH \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
          "restrictions" : {
            "browserKeyRestrictions": {
              "allowedReferrers": "www.example.com"
            }
          },
          "etag": "ETAG"
        }'