Google 使用 Go 进行 Cloud Bigtable 身份验证

Google Cloud Bigtable authentication with Go

我正在尝试插入一个简单的记录,就像在 GoDoc 中一样。但是这个returns,

rpc error: code = 7 desc = "User can't access project: tidy-groove"

当我搜索 grpc 代码时,它说..

PermissionDenied Code = 7

// Unauthenticated indicates the request does not have valid
// authentication credentials for the operation.

我在我的控制台中启用了 Big table 并创建了一个集群和一个服务帐户并收到了 json。我在这里做错了什么?

package main

import (
"fmt"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"google.golang.org/cloud"
"google.golang.org/cloud/bigtable"
"io/ioutil"
)

func main() {
fmt.Println("Start!")
put()
}

func getClient() *bigtable.Client {
jsonKey, err := ioutil.ReadFile("TestProject-7854ea9op741.json")
if err != nil {
    fmt.Println(err.Error())
}

config, err := google.JWTConfigFromJSON(
    jsonKey,
    bigtable.Scope,
) // or bigtable.AdminScope, etc.

if err != nil {
    fmt.Println(err.Error())
}

ctx := context.Background()
client, err := bigtable.NewClient(ctx, "tidy-groove", "asia-east1-b", "test1-bigtable", cloud.WithTokenSource(config.TokenSource(ctx)))

if err != nil {
    fmt.Println(err.Error())
}

return client
}

func put() {
ctx := context.Background()
client := getClient()
tbl := client.Open("table1")
mut := bigtable.NewMutation()
mut.Set("links", "maps.google.com", bigtable.Now(), []byte("1"))
mut.Set("links", "golang.org", bigtable.Now(), []byte("1"))
err := tbl.Apply(ctx, "com.google.cloud", mut)
if err != nil {
    fmt.Println(err.Error())
}
}

看看:helloworld.go or search.go 使用了 GOOGLE_APPLICATION_CREDENTIALS 环境变量。

对于大多数环境,您甚至不再需要设置 GOOGLE_APPLICATION_CREDENTIALSGoogle Cloud PlatformManaged VMsGoogle App Engine 都有为您准备的正确的东西。如果您使用 gcloud init 或其前身 gcloud auth login 后跟 gcloud config set project <projectID>.

,您的桌面环境也将是正确的

我已经解决了这个问题。代码没有问题,但是config json本身。所以任何想要验证身份并通过 google 搜索来到这里的人...这段代码是正确的并且工作完美。我做错了如下。

首先,我创建了一个服务帐户并获得了 json。但是 google 警告我我不是项目的所有者因此它不会被添加到接受列表但是无论如何它让我下载 json。 然后我从控制台删除了那个密钥,并请求项目所有者为我创建一个密钥。 他在那里创建了另一个与我给定的名称相同的密钥。由于他是所有者,因此没有显示 error/warning 消息并成功下载了 json 文件。

当我尝试这样做时...我的问题开始了。那是我发布这个问题的时候。 之后没有解决方案。我要求所有者删除该密钥并创建另一个密钥但名称不同..

然后成功了!似乎如果您尝试使用非所有者帐户创建密钥然后再次使用相同名称创建(当然在删除原始帐户之后)没有任何效果。希望这对大家有帮助:)