我正在尝试使用gcloud CLI所使用的相同凭据将消息发布到GCP PubSub,但没有成功。

我可以确认可以通过以下方式张贴到主题
gcloud pubsub topics publish myTopic --project "myProject" --message "Hello World!"
但是,当我尝试使用下面的代码使用与gcloud完全相同的凭据时

creds, err := google.FindDefaultCredentials(context.Background())
if err != nil {
    panic(fmt.Sprintf("Unable to retrieve default credentials: %v", err))
}
client, err := pubsub.NewClient(ctx, "myproject", option.WithCredentials(creds))
if err != nil {
    panic(fmt.Sprintf("unable to create GCP storage client: %v", err))
}
topic := client.Topic("myTopic")
r := topic.Publish(ctx, &pubsub.Message{
    Data: []byte("Hello World!"),
})
_, err = r.Get(ctx)
if err != nil {
    panic(fmt.Sprintf("failed to publish message: %v", err))
}

我收到以下错误消息
panic: failed to publish message: rpc error: code = Unauthenticated desc = transport: oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error": "invalid_grant",
  "error_description": "Bad Request"
}

我还尝试过直接加载json文件,以确保它未在某处获取其他默认凭据,但出现了相同的错误。

如何使用与gcloud CLI相同的凭据来发布到我有权访问的pubsub主题?

最佳答案

您是否尝试过模拟输入服务帐户选项? [1]
也许这就是您想要的。希望能有所帮助...

[1] https://cloud.google.com/sdk/gcloud/reference#--impersonate-service-account

关于go - 如何使用个人(gcloud)凭据发布到PubSub,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60613512/

10-12 04:36