I have some scripts designed to perform basic troubleshooting and admin tasks in GCP. The authentication is handled via Google Default Application credentials, where the user runs this command:
gcloud auth application-default login
This creates a credentials file, which is $HOME/.config/gcloud/application_default_credentials.json in similar. Alternately, they can authenticate as a service account by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable. In my Python code, I read the credentials and retrieve an access token:
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
access_token = credentials.get_access_token().access_token
Which I can then use to make HTTPS calls as the user, using IAM permissions in GCP to control access to projects and resources.
Problem is, oauth2client has been deprecated since 2019. The recommended replacement is google-auth. I had a heck of a time finding a simple real-world example get the access token, but here it is. The trick is use default() to get the credentials, then refresh() to generate a fresh access token:
from google.auth import default
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
credentials, project_id = default(scopes=SCOPES, quota_project_id='xxxxxx')
credentials.refresh(Request())
access_token = credentials.token
An alternate solution is use Credentials.from_authorized_user_file() to read the credentials. It is faster, but takes some extra work to determine the location of the JSON file. Assuming GOOGLE_APPLICATION_CREDENTIALS is set:
from os import environ
from google.oauth2.credentials import Credentials
_ = environ.get('GOOGLE_APPLICATION_CREDENTIALS')
credentials = Credentials.from_authorized_user_file(_, scopes=SCOPES)
BTW, to instead use a Service Account for authentication, just use these two lines instead:
from google.oauth2.service_account import Credentials
credentials = Credentials.from_service_account_file(_, scopes=SCOPES)