TL;DR
Don’t hardcode your Google Drive API credentials in your script! Use environment variables and a service account with restricted permissions for the best security. This guide shows you how.
Sharing Google Drive API Credentials Securely
- Create a Service Account:
- Go to the Google Cloud Console’s IAM & Admin > Service Accounts page.
- Click “+ CREATE SERVICE ACCOUNT”.
- Give your service account a name and description.
- Grant it the necessary permissions (e.g., Drive Read Only, Drive File Maker). Be as restrictive as possible! Don’t give full drive access unless absolutely needed.
- Click “CREATE KEY”. Choose JSON as the key type and click “CREATE”. Keep this file safe! It contains your credentials.
- Enable the Drive API:
- In the Google Cloud Console, go to APIs & Services > Library.
- Search for “Google Drive API” and enable it.
- Store Credentials as Environment Variables:
Never commit your JSON key file to version control! Instead, use environment variables.
- Set the following environment variables:
GOOGLE_APPLICATION_CREDENTIALS: Point this to the full path of your downloaded JSON key file. For example:/home/user/my-drive-credentials.json- (Optional) If you need other credentials, set them as environment variables too (e.g., client ID, client secret).
- How to set environment variables:
- Linux/macOS: Add lines like
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.jsonto your~/.bashrcor~/.zshrcfile, then runsource ~/.bashrcorsource ~/.zshrc. - Windows: Use the System Properties dialog (search for “environment variables” in the Start Menu) to add new user or system variables.
- Linux/macOS: Add lines like
- Set the following environment variables:
- Access Credentials in Your Script (Python Example):
Use a library like
google-authto automatically load credentials from the environment.from google.oauth2 import service_account credentials = service_account.Credentials.from_environment() # Now you can use 'credentials' with your Google Drive API calls. print(credentials) - Restrict Service Account Access (Important):
- In the Google Cloud Console, review the service account’s permissions. Ensure it only has access to the specific folders and files your script needs.
- Consider using IAM Conditions for even more granular control (e.g., restrict access based on time of day).
- Regularly Rotate Keys:
For enhanced security, periodically rotate your service account keys. Delete old keys after creating new ones.

