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

Google App Engine Go 1.11 应用程序无法访问 Google 电子表格

Google App Engine Go 1.11 应用程序无法访问 Google 电子表格

Go
吃鸡游戏 2023-05-15 15:10:48
我正在尝试从在Google App Engine Go 1.11 Standard Environment上运行的应用程序通过 API 访问 google 电子表格。不幸的是,应用程序无法读取此电子表格。我在Spreadsheets.Values.Get通话中遇到下一个错误:googleapi: Error 403: Request had insufficient authentication scopes., forbidden示例代码// Sample app showing issue with GAE -> google spreadsheetspackage mainimport (    "context"    "fmt"    "log"    "net/http"    "os"    "cloud.google.com/go/compute/metadata"    "golang.org/x/oauth2/google"    "google.golang.org/api/sheets/v4")func main() {    http.HandleFunc("/", indexHandler)    // [START setting_port]    port := os.Getenv("PORT")    if port == "" {        port = "8080"        log.Printf("Defaulting to port %s\n", port)    }    // let's check app engine instance scopes    scopes, _ := metadata.Get("instance/service-accounts/default/scopes")    log.Printf("[DEBUG] metadata scopes: %s.\n", scopes)    log.Printf("Listening on port %s", port)    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))    // [END setting_port]}// indexHandler responds to requests with our greeting.func indexHandler(w http.ResponseWriter, r *http.Request) {    ctx := context.Background()    client, _ := google.DefaultClient(ctx, "https://www.googleapis.com/auth/spreadsheets.readonly")    srv, err := sheets.New(client)    // Prints the names and majors of students in a sample spreadsheet:    // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit    spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"    readRange := "Class Data!A2:E"    resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()    if err != nil {        log.Fatalf("Unable to retrieve data from sheet: %v\n", err)    }重现步骤:1) 部署应用程序:gcloud app deploy2) 在浏览器中打开(您将获得 502):gcloud app browse3) 检查日志:gcloud app logs read
查看完整描述

1 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

我之前也遇到过这个问题以及 App Engine 到 G Suite 的集成。您需要使用服务帐户密钥。默认的是不够的(我相信是因为它没有私钥,但这可能是错误的)。


本质上,您需要使用您的代码上传一个密钥并使用它来获取Client(而不是使用默认密钥):


func getOauthClient(serviceAccountKeyPath string) *http.Client {

    ctx := context.Background()

    data, err := ioutil.ReadFile(serviceAccountKeyPath)

    if err != nil {

        log.Fatal(err)

    }

    creds, err := google.CredentialsFromJSON(ctx, data, "https://www.googleapis.com/auth/spreadsheets.readonly")

    if err != nil {

        log.Fatal(err)

    }


    return oauth2.NewClient(ctx, creds.TokenSource)

}


查看完整回答
反对 回复 2023-05-15
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信