在Golang中调用google.apps.sheets.v4.SpreadsheetsService.GetValues时出现访问令牌范围不足

ss2ws0br  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(197)

我正在尝试运行一个简单的go程序,调用GoogleSheets API:

package main

import (
    "context"
    "fmt"

    "google.golang.org/api/sheets/v4"
)

func main() {
    ctx := context.Background()

    srv, err := sheets.NewService(ctx)
    if err != nil {
        panic(err)
    }

    resp, err := srv.Spreadsheets.Values.Get("1HG_cmqALkquc0ud8Pm7GKOhR5IpPSj20q_fFkHBaM5M", "A1").Do()
    if err != nil {
        panic(err)
    }
    fmt.Println(fmt.Sprintf("%+v", resp.Values))
}

但当我试着运行它时,我得到:

$ rm /home/johan/.config/gcloud/application_default_credentials.json
$ gcloud auth application-default login
Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=W...s&access_type=offline&code_challenge=q...4&code_challenge_method=S256

Credentials saved to file: [/home/johan/.config/gcloud/application_default_credentials.json]

These credentials will be used by any library that requests Application Default Credentials (ADC).

Quota project "questions-279902" was added to ADC which can be used by Google client libraries for billing and quota. Note that some services may still bill the project owning the resource.

$ go run sheets_api.go 
panic: googleapi: Error 403: Request had insufficient authentication scopes.
Details:
[
  {
    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
    "domain": "googleapis.com",
    "metadata": {
      "method": "google.apps.sheets.v4.SpreadsheetsService.GetValues",
      "service": "sheets.googleapis.com"
    },
    "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"
  }
]

More details:
Reason: insufficientPermissions, Message: Insufficient Permission

goroutine 1 [running]:
main.main()
        /home/johan/20q/cmd/labelserver/sheets_api.go:20 +0x194
exit status 2

我创建了此Google工作表,因此我的用户应该可以访问它。
我哪里做错了?

nlejzf6q

nlejzf6q1#

在Go语言中,您可以像这样限定令牌的范围

...
func main() {
    ctx := context.Background()
    cred, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/spreadsheets.readonly")
    srv, err := sheets.NewService(ctx, option.WithCredentials(cred))
...

然而,你可能(应该?)会有后续的错误。我wrote that article提到了Cloud Build的Sheet访问问题(基于Python,因为大多数开发都使用Python,但我是一个Go开发人员,如果你需要的话,我可以在Go中帮助你)。
本文介绍了不同的方法来限定令牌的范围,其中一种方法将根据底层环境为您工作。

相关问题