Skip to content

Instantly share code, notes, and snippets.

@jeffbryner
Created December 17, 2023 21:57
Show Gist options
  • Save jeffbryner/a43e82df066b9b5c6a209c63e726568b to your computer and use it in GitHub Desktop.
Save jeffbryner/a43e82df066b9b5c6a209c63e726568b to your computer and use it in GitHub Desktop.
google delegated creds from a gcp service account
def delegated_credential(credentials, subject, scopes):
from google.auth import iam
from google.auth.transport import requests
from google.oauth2 import service_account
TOKEN_URI = "https://accounts.google.com/o/oauth2/token"
try:
admin_creds = credentials.with_subject(subject).with_scopes(scopes)
except AttributeError: # Looks like a compute creds object
# Refresh the boostrap credentials. This ensures that the information
# about this account, notably the email, is populated.
request = requests.Request()
credentials.refresh(request)
# Create an IAM signer using the bootstrap credentials.
signer = iam.Signer(request, credentials, credentials.service_account_email)
# Create OAuth 2.0 Service Account credentials using the IAM-based
# signer and the bootstrap_credential's service account email.
admin_creds = service_account.Credentials(
signer,
credentials.service_account_email,
TOKEN_URI,
scopes=scopes,
subject=subject,
)
except Exception:
raise
return admin_creds
@jeffbryner
Copy link
Author

Use to allow a cloudrun container to use it's service account to instantiate delegated credentials
without having to export JSON for the service account and import using service_account

Code like thus:

credentials, project = google.auth.default()
service_creds = delegated_credential(
credentials=credentials,
subject="[email protected]",
scopes=SCOPES,
)
service = build("calendar", "v3", credentials=service_creds)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment