在GCP上使用Pubsub时如何解决认证范围不足的问题

How to solve insufficient authentication scopes when use Pubsub on GCP

我正在尝试构建 2 个微服务(在 Java Spring 引导中)以使用 GCP Pub/Sub.

相互通信

首先,我测试了程序(在 Eclipse 中)在我的本地笔记本电脑(http://localhost)中按预期工作,即一个微服务发布了消息,另一个微服务使用创建的 Topic/Subscriber 成功接收了消息在 GCP 中(以及凭证私钥:mypubsub.json)。

然后,我将相同的程序部署到 运行 GCP,并得到以下错误:

- 2020-03-21 15:53:16.831 WARN 1 --- [bsub-publisher2] o.s.c.g.p.c.p.PubSubPublisherTemplate : Publishing to json-payload-sample-topic topic failed
- com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Request had insufficient authentication scopes. at com.google.api.gax.rpc.ApiExceptionFactory

我将程序(在容器中)部署到 GCP/Kubernetes 引擎上的 运行 所做的工作:

  1. 切换到我的项目进行 Pubsub 测试后登录云 Shell
  2. Git 克隆我在 Eclipse 中测试的程序
  3. 将 mypubsub.json 文件移动到 /home/my_user_id
  4. 导出 GOOGLE_APPLICATION_CREDENTIALS="/home/my_user_id/mp6key.json"
  5. 运行 'mvn clean package' 构建微服务程序
  6. 运行 'docker build' 创建图像文件
  7. 运行 'docker push' 将图像文件推送到 gcr.io repo
  8. 运行 'kubectl create' 创建部署并公开服务

一旦部署并公开了 2 个微服务,当我尝试在浏览器中访问它们时,发布消息的那个可以很好地从数据库检索数据并处理数据,然后在尝试访问时失败并出现上述错误GCP Pubsub API 发布消息

任何人都可以提供有关检查内容以解决问题的提示吗?

问题已按照指南解决:

https://cloud.google.com/kubernetes-engine/docs/tutorials/authenticating-to-cloud-platform

简单的解决方案是在 deployment.yaml 中添加以下行以加载凭证密钥:

        - name: google-cloud-key
          secret:
            secretName: pubsub-key
        containers:
        - name: my_container
          image: gcr.io/my_image_file
          volumeMounts:
          - name: google-cloud-key
            mountPath: /var/secrets/google
          env:
          - name: GOOGLE_APPLICATION_CREDENTIALS
            value: /var/secrets/google/key.json

尝试向您的 Publisher class 明确提供 CredentialsProvider,我遇到了同样的身份验证问题。

这种方法对我有用!

CredentialsProvider credentialsProvider =
FixedCredentialsProvider.create(
ServiceAccountCredentials.fromStream(PubSubUtil.class.getClassLoader().getResourceAsStream("key.json")));
Publisher publisher = Publisher.newBuilder(topicName).setCredentialsProvider(credentialsProvider).build();