How do I use a GCloud Access Token with the Python SDK?

688 views Asked by At

I can obtain an access token for a service account using

gcloud auth print-access-token --impersonate-service-account=<my-service-account>

Assuming I have such a token from somewhere (e.g. in an environment variable), how do I use it to authenticate with e.g. the Google Cloud Storage Client SDK?

I've looked through documentation of various packages in the Google Auth package, but I've found none that seem to accept a token as an authorization method.

2

There are 2 answers

6
CloudBalancing On

I'm not sure access token is enough for the Python SDK if you take a look at the code you need to supply more config data such as project-id and more... (also possible to set via environment but needs to be done). Generally if you are setting all the correct env vars auth should work using the token.

What is the error you are getting maybe you are missing some other config?

0
Arnaud P On

I've been able to get and use a GCloud Access Token in python as follows (process owner needs the Service Account Token Creator permission for that service):

from google.cloud.iam_credentials_v1 import IAMCredentialsClient
from google.oauth2.credentials import Credentials
import googleapiclient.discovery

response = IAMCredentialsClient().generate_access_token(
    name=f'projects/-/serviceAccounts/{service_id}',
    scope=['https://www.googleapis.com/auth/gmail.insert'],
)
service = googleapiclient.discovery.build(
    'gmail',
    'v1',
    credentials=Credentials(response.access_token), <= use your token here
)

Unfortunately, I'm having trouble setting up Domain-wide delegation with this syntax.