Search code examples
gogoogle-cloud-platformpublish-subscribe

How to publish to pubsub with Service Account Key JSON vs Service Account JSON


Is this possible?

When I attempt to use the following Service Account Key JSON:

{
 "keyAlgorithm": "KEY_ALG_RSA_2048",
 "keyOrigin": "GOOGLE_PROVIDED",
 "name": "projects/XXXX",
 "privateKeyData": "XXXXXX",
 "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
 "validAfterTime": "2019-08-16T19:45:25Z",
 "validBeforeTime": "2029-08-13T19:45:25Z"
}

I get the following error:

client: pubsub: google: error getting credentials using GOOGLE_APPLICATION_CREDENTIALS environment variable: missing 'type' field in credentials

Am I missing something? It apparently only wants to work with Service Account JSON. I'd rather not hand out those credentials.

Any advice?


Solution

  • The reason for the error is that you are using the raw output from the API service.projects.serviceAccounts.keys.create.

    Look at the output in your question. The key privateKeyData contains the base64 encoded value of the service account JSON key file. Base64 decode that value and use as JSON for input when creating credentials.

    Python Example:

    from google.oauth2 import service_account
    info = json.loads(base64.b64decode(privateKeyData))
    credentials = service_account.Credentials.from_service_account_info(info)
    

    Go Example:

    import b64 "encoding/base64"
    import "golang.org/x/oauth2/google"
    scope := "https://www.googleapis.com/auth/cloud-platform"
    s, _ := b64.StdEncoding.DecodeString(privateKeyData)
    ctx := context.Background()
    creds, err := google.CredentialsFromJSON(ctx, s, scope)