Skip to content

Demystifying GCP Authentication: Keys, OAuth, and Service Accounts for Your Google Cloud Projects

ShamsherAI Keys OAuth Shamsher Haider Bigdata AI ML Cloud AWS GCP

When working with Google Cloud Platform (GCP) or other APIs in your Python projects, secure access is paramount. Here, I’ll explore three common authentication methods: API keys, OAuth, and service accounts. Let us walk through with Python code examples to illustrate their usage scenarios.

Understanding the Toolbox

  • API Keys: Simple strings that identify your application for basic API access. They are convenient for public APIs but lack user identification and are not ideal for sensitive data.
  • OAuth: An authorization framework that delegates user authentication to a trusted third-party (like Google). It offers granular control and user consent, making it suitable for user-centric applications.
  • Service Accounts: Google-managed identities for your applications within a project. They use private keys for authentication and offer the highest security due to their non-reliance on user credentials.

1. Using API Keys (Public APIs Example):

Let’s access weather data from the OpenWeatherMap API using an API key:

import requests

# Replace with your API key
api_key = "YOUR_API_KEY"
city = "London"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"

response = requests.get(url)

if response.status_code == 200:
  data = response.json()
  print(f"Current weather in {city}: {data['weather'][0]['description']}")
else:
  print("Error fetching weather data")

This code retrieves weather information for a city using an API key. Remember to replace YOUR_API_KEY with your actual key.

2. OAuth: User Authentication (Google Drive API Example):

Here’s a simplified example (refer to Google’s documentation for full implementation) demonstrating user authentication for accessing Google Drive with OAuth:

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# Replace with your credentials file path
credentials_path = "credentials.json"

# Set up OAuth flow
scopes = ["https://www.googleapis.com/auth/drive.readonly"]
flow = InstalledAppFlow.from_client_secrets_file(credentials_path, scopes=scopes)

# User authorization (omitted for simplicity)

service = build("drive", "v3", credentials=credentials)

# List files in user's Drive
results = service.files().list().execute()
print(f"Files in your Drive:")
for file in results.get('files', []):
  print(file['name'])

This example outlines the setup for OAuth authentication using a credentials file and demonstrates how to access user data (Drive files) after successful authorization.

3. Service Accounts: Secure Application Access (GCP Cloud Storage Example):

Let’s interact with Google Cloud Storage (GCS) securely using a service account:

from google.cloud import storage

# Replace with your project ID and service account key path
project_id = "YOUR_PROJECT_ID"
service_account_key_path = "service_account.json"

# Set up authentication
credentials = storage.Client.from_service_account_json(
    service_account_key_path)

# Create a storage client
client = storage.Client(project=project_id, credentials=credentials)

# Upload a file to a bucket (replace bucket_name and filename)
bucket = client.bucket("your-bucket-name")
blob = bucket.blob("your_file.txt")
blob.upload_from_filename("your_file.txt")

print("File uploaded successfully!")

This code demonstrates uploading a file to a GCS bucket using a service account key for authentication. Remember to replace placeholders with your project details and key path.

Choosing the Right Tool

  • API Keys: Ideal for public APIs with limited access needs.
  • OAuth: Perfect for user-centric applications requiring user authorization.
  • Service Accounts: Best suited for secure access within your GCP projects by applications.

By understanding these authentication methods and their strengths, you can make informed decisions to secure your GCP projects interacting with APIs. Do refer to the official documentation for in-depth implementation details for each method.