How to retrieve access-token from GCP Golang SDK?


We are implementing an application for GCP which needs the oauth2 bearer token to authenticate docker against GCR. The application is written in Go and it uses the GCP SDK for Golang.

I’d like to get what gcloud auth print-access-token give from the SDK, but I don’t find how to do it…


Have a look at oauth2/google.

You may (!?) be able to use workload identity federation (using this library too and thereby avoid using a Google Service Account key) but, using a Service Account (with roles/storage.objectAdmin see GCR: Granting IAM roles) and Application Default Credentials (export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json) look at DefaultTokenSource.

The Token returned by Token() from TokenSource gives you an access_token (and refresh_token and expiry).


You can use the Service Account key file directly to authenticate a Docker client to GCR. This would simplify your code (and avoid refreshing). The document reiterates the caution in using Service Account keys.

Answered By – DazWilkin

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.