在 Golang 中获取谷歌云服务帐户的访问令牌?

我在谷歌云上使用服务帐户。出于某种原因,我想在 golang 中以编程方式获取访问令牌。我可以gcloud auth application-default print-access-token在命令行上做。


谷歌有一个图书馆似乎可以让我获得令牌。这是我尝试使用它的方法:


    credentials, err := auth.FindDefaultCredentials(ctx)

    if err == nil {

        glog.Infof("found default credentials. %v", credentials)

        token, err2 := credentials.TokenSource.Token()

        fmt.Printf("token: %v, err: %v", token, err2)

        if err2 != nil {

            return nil, err2

        }

但是,我收到一条错误消息token: <nil>, err: oauth2: cannot fetch token: 400 Bad Request。


我已经GOOGLE_APPLICATION_CREDENTIALS定义了 env 变量并指向 json 文件。


犯罪嫌疑人X
浏览 191回答 1
1回答

陪伴而非守候

按原样运行代码,返回错误:Invalid OAuth scope or ID token audience provided我从Google 的 OAuth 范围添加了 catch-all Cloud Platform 可写范围:https://www.googleapis.com/auth/cloud-platform这样做,似乎有效。见下文:package mainimport (&nbsp; &nbsp; "context"&nbsp; &nbsp; "log"&nbsp; &nbsp; "golang.org/x/oauth2"&nbsp; &nbsp; auth "golang.org/x/oauth2/google")func main() {&nbsp; &nbsp; var token *oauth2.Token&nbsp; &nbsp; ctx := context.Background()&nbsp; &nbsp; scopes := []string{&nbsp; &nbsp; &nbsp; &nbsp; "https://www.googleapis.com/auth/cloud-platform",&nbsp; &nbsp; }&nbsp; &nbsp; credentials, err := auth.FindDefaultCredentials(ctx, scopes...)&nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("found default credentials. %v", credentials)&nbsp; &nbsp; &nbsp; &nbsp; token, err = credentials.TokenSource.Token()&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("token: %v, err: %v", token, err)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Print(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}我最近在使用这个库时遇到了一些挑战(访问需要 JWT 受众的 Cloud Run 服务)。在朋友的推荐下,我改用了google.golang.org/api/idtoken。API 非常相似。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go