Blog | G5 Cyber Security

Secure Google Drive API Credentials

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

  1. 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.
  2. Enable the Drive API:
  3. 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.json to your ~/.bashrc or ~/.zshrc file, then run source ~/.bashrc or source ~/.zshrc.
      • Windows: Use the System Properties dialog (search for “environment variables” in the Start Menu) to add new user or system variables.
  4. Access Credentials in Your Script (Python Example):

    Use a library like google-auth to 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)
    
  5. 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).
  6. Regularly Rotate Keys:

    For enhanced security, periodically rotate your service account keys. Delete old keys after creating new ones.

Exit mobile version