Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent for gcloud auth print-identity-token command

The gcloud auth print-identity-token command prints an identity token for the specified account.

$(gcloud auth print-identity-token \
        --audiences=https://example.com \
        --impersonate-service-account [email protected] \
        --include-email)

How do I do the same using Python?

like image 717
nipy Avatar asked Apr 02 '26 04:04

nipy


1 Answers

Here a code sample (not so easy and well documented)

import google.auth.transport.requests
from google.auth.impersonated_credentials import IDTokenCredentials
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']

request = google.auth.transport.requests.Request()

audience = 'my_audience'

creds, _ = google.auth.default(scopes=SCOPES)
icreds = google.auth.impersonated_credentials.Credentials(
        source_credentials=creds,
        target_principal="SA TO IMPERSONATE",
        target_scopes=SCOPES)

id = IDTokenCredentials(icreds, target_audience=audience,include_email=True)
id.refresh(request)
print(id.token)
like image 63
guillaume blaquiere Avatar answered Apr 08 '26 05:04

guillaume blaquiere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!