为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用个人 (gcloud) 凭据发布到 PubSub

如何使用个人 (gcloud) 凭据发布到 PubSub

Go
拉丁的传说 2022-05-23 14:48:19
我正在尝试使用与gcloudCLI 相同的凭据向 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 RequestResponse: {  "error": "invalid_grant",  "error_description": "Bad Request"}我还尝试直接加载 json 文件,以确保它没有在某处获取其他默认凭据,但出现相同的错误。如何使用与 gcloud CLI 相同的凭据发布到我有权访问的 pubsub 主题?
查看完整描述

3 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

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

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


查看完整回答
反对 回复 2022-05-23
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

当我配置我的本地环境时,我正在这样做

  • 运行命令:gcloud auth application-default login

  • 单击链接并分配 Google Auth Library

命令的结果应该显示如下

Credentials saved to file: [/path/to/application_default_credentials.json]
These credentials will be used by any library that requests Application Default Credentials (ADC).
  • 复制/path/to/application_default_credentials.json

  • GOOGLE_APPLICATION_CREDENTIALS使用此值创建环境变量。在 Linux 中:export GOOGLE_APPLICATION_CREDENTIALS=/path/to/application_default_credentials.json

现在,您的个人凭据也被定义为在本地环境中运行的应用程序的默认凭据。


查看完整回答
反对 回复 2022-05-23
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

您需要在 Go 脚本中设置身份验证。默认情况下,它将使用与运行代码的环境中存在的凭据相同的凭据。


这是在创建存储桶时使用默认凭据设置新客户端的示例:


package main


import (

    "context"

    "fmt"

    "log"

    "time"


    "cloud.google.com/go/storage" 



func main() {

    ctx := context.Background()


    // Sets your Google Cloud Platform project ID.

    projectID := "YOUR_PROJECT_ID"


    // Creates a client.

    client, err := storage.NewClient(ctx)

    if err != nil {

            log.Fatalf("Failed to create client: %v", err)

    }

因此,请在您的代码中尝试此操作:


ctx := context.Background()

client := pubsub.NewClient(ctx)


查看完整回答
反对 回复 2022-05-23
  • 3 回答
  • 0 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号