Get service account auth token without gcloud?

There is no need for a library or an api. You can obtain it using

curl -s "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google" | jq -r .access_token

It is useful if you need it in a shell script.


For your second question, “is there some way to generate long-lived tokens with gcloud?”, no there is not. However, you can use a refresh token to generate new access tokens. Check the first answer for this question:

OAuth2 and Google API: Access token expiration time?

And also, here’s an example of a python library that you can use as an authentication mechanism:

https://github.com/GoogleCloudPlatform/google-auth-library-python/blob/master/google/oauth2/credentials.py


I think that this is exactly what you are looking for:

https://developers.google.com/identity/protocols/OAuth2#serviceaccount

Honestly I don't think that what you were trying to achieve was correct, running

gcloud auth application-default print-access-token

you get a token that is not intended to do what you were looking for:

"This command is useful when you are developing code that would normally use a service account but need to run the code in a local development environment where it's easier to provide user credentials."

This should guide you a bit more in the implementation of this solution: https://developers.google.com/identity/protocols/OAuth2ServiceAccount


Here's what it looks like in golang:

import(
    "google.golang.org/api/compute/v1"
    "google.golang.org/api/container/v1"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
    "google.golang.org/api/transport"
)
ctx := context.Background()
creds, err := transport.Creds(ctx, option.WithScopes(compute.CloudPlatformScope))
token, err := creds.TokenSource.Token()