Service Account Setup¶
Service accounts are useful for server-to-server authentication without user interaction.
When to Use Service Accounts¶
- Automated scripts that run without user presence
- Backend services that access Google APIs
- Domain-wide delegation for G Suite/Workspace admins
Creating a Service Account¶
- Go to Google Cloud Console
- Select your project
- Navigate to IAM & Admin > Service Accounts
- Click Create Service Account
- Fill in the details:
- Name:
gsuite-service - ID: auto-generated
- Click Create and Continue
- (Optional) Grant roles if needed
- Click Done
Generating a Key¶
- Click on your new service account
- Go to Keys tab
- Click Add Key > Create new key
- Select JSON
- Save the file as
service-account.json
⚠️ Never commit this file! It's in
.gitignoreby default.
Using with google-suite¶
from gsuite_core import GoogleAuth
# From service account file
auth = GoogleAuth.from_service_account("service-account.json")
# Use with any client
from gsuite_gmail import Gmail
gmail = Gmail(auth)
Domain-Wide Delegation¶
For accessing other users' data in a Workspace domain:
- In Google Cloud Console, edit your service account
- Enable Domain-wide delegation
- Note the Client ID
- In Google Admin Console:
- Go to Security > API Controls > Domain-wide Delegation
- Add new API client
- Enter the Client ID
- Add required scopes
# Impersonate a user
auth = GoogleAuth.from_service_account(
"service-account.json",
subject="user@yourdomain.com" # User to impersonate
)
Security Best Practices¶
- Rotate keys regularly
- Use minimal scopes required for your use case
- Store keys securely (Secret Manager, environment variables)
- Never commit service account keys to git
- Audit usage in Cloud Console
Environment Variables¶
export GOOGLE_APPLICATION_CREDENTIALS="path/to/service-account.json"
Or configure in code:
auth = GoogleAuth.from_service_account(
credentials_file="path/to/service-account.json"
)