These instructions apply for non Google Cloud Platform (GCP) APIs. If you're building a GCP application, see using API keys for GCP.
When you use API keys in your Google Cloud Platform (GCP) applications, take care to keep them secure. Publicly exposing your credentials can result in your account being compromised, which could lead to unexpected charges on your account. To keep your API keys secure, follow these best practices:
- Do not embed API keys directly in code: API keys that are embedded in code can be accidentally exposed to the public, for example, if you forget to remove the keys from code that you share. Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree.
- Do not store API keys in files inside your application's source tree: If you store API keys in files, keep the files outside your application's source tree to help ensure your keys do not end up in your source code control system. This is particularly important if you use a public source code management system such as GitHub.
- Restrict your API keys to be used by only the IP addresses, referrer URLs, and mobile apps that need them: By restricting the IP addresses, referrer URLs, and mobile apps that can use each key, you can reduce the impact of a compromised API key. You can specify the hosts and apps that can use each key from the GCP Console Credentials page and then create a new API key with the settings you want, or edit the settings of an existing API key.
- Restrict your API keys to be usable only for certain APIs: If you have multiple APIs enabled in your project and your API key should only be used with some of them, restrict usage of that key to those APIs. You can specify the allowed APIs for each key from the GCP Console Credentials page and then create a new API key with the settings you want, or edit the settings of an existing API key.
- Delete unneeded API keys: To minimize your exposure to attack, delete any API keys that you no longer need.
- Rotate your API keys periodically: To rotate your API keys, call the CreateKey method. After the replacement keys are created, update your applications to use the newly-generated keys and delete the old keys.